mybatis

Mybatis的简述

MyBatis 是一款优秀的持久层框架,避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程,可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 实体类 【Plain Old Java Objects,普通的 Java对象】映射成数据库中的记录。

MyBatis 是一个半自动化的ORM框架 (Object Relationship Mapping) →对象关系映射

Mybatis的依赖导入以及文件配置

Mybatis的依赖

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.2</version>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
</dependency>

连接数据库的配置datasourse.properties

driver=com.mysql.jdbc.Driver
#Mysql8.0+ 需要添加时区配置 &serverTimezone=Asia/shanghai
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
username=root
password=123456

Mybatis的核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
       PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
   <!--导入properties文件-->
   <properties resource="db.properties"/>

   <environments default="development">
       <environment id="development">
           <transactionManager type="JDBC"/>
           <dataSource type="POOLED">
               <property name="driver" value="${driver}"/>
               <property name="url" value="${url}"/>
               <property name="username" value="${username}"/>
               <property name="password" value="${password}"/>
           </dataSource>
       </environment>
   </environments>
   <mappers>
       <mapper resource="mapper/UserMapper.xml"/>
   </mappers>
</configuration>

Mybatis的CRUD操作

Mybatis的工具类

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

   private static SqlSessionFactory sqlSessionFactory;

   static {
       try {
           String resource = "mybatis-config.xml";
           InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      } catch (IOException e) {
           e.printStackTrace();
      }
  }

   //获取SqlSession连接
   public static SqlSession getSession(){
       return sqlSessionFactory.openSession();
  }

}

实体类例子

public class User {

   private int id;  //id
   private String name;   //姓名
   private String pwd;   //密码

   //构造,有参,无参
   //set/get
   //toString()

}

Mapper接口类

import top.hcode.pojo.User;
import java.util.List;

public interface UserMapper {
   List<User> selectUser();
   //添加一个用户
   int addUser(User user);
   //修改一个用户
   int updateUser(User user);
   //根据id删除用户
   int deleteUser(int id);
}

Mapper.xml书写SQL语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
       PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.hcode.dao.UserMapper">
 <select id="selectUser" resultType="top.hcode.pojo.User"> //id为对应UserMapper的方法名
  select * from user
 </select>
 <insert id="addUser" parameterType="top.hcode.pojo.User">
    insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="top.hcode.pojo.User">
  update user set name=#{name},pwd=#{pwd} where id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
  delete from user where id = #{id}
</delete>
</mapper>

添加Maven静态资源过滤

<resources>
   <resource>
       <directory>src/main/java</directory>
       <includes>
           <include>**/*.properties</include>
           <include>**/*.xml</include>
       </includes>
       <filtering>false</filtering>
   </resource>
   <resource>
       <directory>src/main/resources</directory>
       <includes>
           <include>**/*.properties</include>
           <include>**/*.xml</include>
       </includes>
       <filtering>false</filtering>
   </resource>
</resources>

测试

public class MyTest {
   @Test
   public void selectUser() {
       SqlSession session = MybatisUtils.getSession();
       //方法一:
       //List<User> users = session.selectList("top.hcode.mapper.UserMapper.selectUser");
       //方法二:
       UserMapper mapper = session.getMapper(UserMapper.class);
       List<User> users = mapper.selectUser();

       for (User user: users){
           System.out.println(user);
      }
       session.close();
       //添加
       User user = new User(5,"HZH","牛逼");
       int i = mapper.addUser(user);
       System.out.println(i);
       session.commit(); //提交事务,重点!不写的话不会提交到数据库
       session.close();
       //更新
       User user = mapper.selectUserById(1);
       user.setPwd("6666");
       int i = mapper.updateUser(user);
       System.out.println(i);
       session.commit(); //提交事务,重点!不写的话不会提交到数据库
       session.close();
       //删除
       int i = mapper.deleteUser(5);
       System.out.println(i);
       session.commit(); //提交事务,重点!不写的话不会提交到数据库
       session.close();
  }
}
所有的增删改操作都需要提交事务!

模糊查询

拼接通配符,防止SQL注入!!!

<select id=”selectlike” parameterType="map">
    select * from foo where bar like "%"#{value}"%"
</select>

评论