mybatis储备知识(基础)
声明:该文章及该分类中的内容均基于正在开发的项目和一本参考书(深入浅出MyBatis技术原理与实战 by 杨开振)
一、mybatis核心组件
SqlSessionFactoryBuilder(构造器):根据配置信息或代码生成SqlSessionFactory(工厂接口);
SqlSessionFactory:依靠工厂生成SqlSession(会话);
SqlSession:是一个既可以发送SQL去执行并返回结果,也可以获取Mapper的接口;主要用途:1.获取映射器,2.直接通过命名信息执行SQL;
SQLMapper:由一个Java接口和XML文件(或注解)构成,需给出对应的SQL和映射规则。它负责发送SQL去执行,并返回结果。
二、构建SqlSessionFactory
有两种构建方式:1.xml配置;2.代码方式
建议使用XML方式:避免重复编译代码,也方便配置人员修改
简易XML配置:(部分可不配置,按需要进行配置)
mybatis-config.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration><!-- org.apache.ibatis.session.Configuration --> 6 <!-- 属性 --> 7 <properties resource="jdbc.properties"/> 8 <settings/> <!--设置 --> 9 <!-- 类型命名 定义别名--> 10 <typeAliases> 11 <typeAlias alias="role" type="com.standard.model.Role"/> 12 </typeAliases> 13 <typeHandlers/><!--类型处理器 --> 14 <objectFactory/><!-- 对象工厂 --> 15 <plugins/><!--插件 --> 16 <environments default="development"><!-- 配置环境 --> 17 <environment id="development"><!-- 环境变量 --> 18 <transactionManager type="JDBC"><!--采用JDBC 事务管理器 --> 19 <property name="autoCommit" value="false"/> 20 </transactionManager> 21 <!-- 数据源 --> 22 <dataSource type="POOLED"> 23 <property name="driver" value="${driver}"/> 24 <property name="url" value="${url}"/> 25 <property name="username" value="${username}"/> 26 <property name="password" value="${password}"/> 27 </dataSource> 28 </environment> 29 </environments> 30 <databaseIdProvider/><!--数据库厂商标识 --> 31 <mappers><!-- 映射器 --> 32 <mapper resource="com/standard/dao/UserMapper.xml"/> 33 </mappers> 34 </configuration>
注意:
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
下面配置映射器时,这个地方有区别
database在jdbc.properties中读取:
1 driver=com.mysql.jdbc.Driver 2 url=jdbc:mysql://localhost:3306/mybatis 3 username=root 4 password=root
注:mybatis的解析程序会将mybatis-config.xml文件配置的信息解析到Configuration类对象里面,然后利用SqlSessionFactoryBuilder读取这个对象为我们创建SqlSessionFactory。
三、创建SqlSession
以下是封装好的工具类,可以直接使用
1 public class SqlSessionFactoryUtil { 2 3 //类线程锁 4 private static final Class CLASS_LOCK =SqlSessionFactoryUtil.class; 5 //私有化构造参数 6 //防止使用者使用new的方式创建多个对象 7 private SqlSessionFactoryUtil(){ } 8 9 //构建SqlSessionFactory 实现单例 10 static SqlSessionFactory sqlSessionFactory=null; 11 12 public static SqlSessionFactory initSqlSessionFactory(){ 13 InputStream iStream = null; 14 //sqlSessionFactory对象 15 SqlSession sqlSession=null; 16 17 //读入配置流文件 加载核心配置文件 18 19 try{ 20 iStream=Resources.getResourceAsStream("mybatis-config.xml"); 21 }catch(IOException e){ 22 // TODO Auto-generated catch block 23 System.out.println("--"+e); 24 e.printStackTrace(); 25 } 26 27 synchronized (CLASS_LOCK) {//避免在多线程环境中,多次初始化造成对象的不唯一 28 if(sqlSessionFactory==null){ 29 //获取SQLSessionFactory 30 sqlSessionFactory=new SqlSessionFactoryBuilder().build(iStream); 31 } 32 33 } 34 return sqlSessionFactory; 35 } 36 37 //打开SqlSession 38 public static SqlSession openSqlSession(){ 39 if(sqlSessionFactory==null){ 40 initSqlSessionFactory(); 41 } 42 return sqlSessionFactory.openSession(); 43 } 44 }
四、映射器(接口+XML注解)
实现方式有两种:1.通过XML文件方式实现(推荐使用)
2.通过代码方式实现:在Configuration里面注册Mapper接口(需要写入Java注解),较为复杂。
先给出接口:UserMapper.java
1 public interface UserMapper { 2 int deleteByPrimaryKey(Integer id); 3 4 int insert(User record); 5 6 int insertSelective(User record); 7 8 User selectByPrimaryKey(Integer id); 9 10 List<User> select(); 11 12 int updateByPrimaryKeySelective(User record); 13 14 int updateByPrimaryKey(User record); 15 16 }
然后给出映射文件:UserMapper.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 <mapper namespace="com.standard.dao.UserMapper"> 4 5 <resultMap id="BaseResultMap" type="com.standard.model.User"> 6 <id column="ID" jdbcType="INTEGER" property="id" /> 7 <result column="ACCOUNT" jdbcType="VARCHAR" property="account" /> 8 <result column="NAME" jdbcType="VARCHAR" property="name" /> 9 <result column="PASSWORD" jdbcType="VARCHAR" property="password" /> 10 <result column="ROLE_ID" jdbcType="INTEGER" property="roleId" /> 11 12 </resultMap> 13 <sql id="Base_Column_List"> 14 ID, ACCOUNT, NAME, PASSWORD, ROLE_ID 15 </sql> 16 <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> 17 select 18 <include refid="Base_Column_List" /> 19 from STANDARD_USER 20 where ID = #{id,jdbcType=INTEGER} 21 </select> 22 <select id="select" resultMap="BaseResultMap"> 23 select 24 <include refid="Base_Column_List"/> 25 from STANDARD_USER 26 </select> 27 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> 28 delete from STANDARD_USER 29 where ID = #{id,jdbcType=INTEGER} 30 </delete> 31 <insert id="insert" parameterType="com.standard.model.User"> 32 insert into STANDARD_USER (ID, ACCOUNT, NAME, 33 PASSWORD, ROLE_ID) 34 values (#{id,jdbcType=INTEGER}, #{account,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, 35 #{password,jdbcType=VARCHAR}, #{roleId,jdbcType=INTEGER}) 36 </insert> 37 <insert id="insertSelective" parameterType="com.standard.model.User"> 38 insert into STANDARD_USER 39 <trim prefix="(" suffix=")" suffixOverrides=","> 40 <if test="id != null"> 41 ID, 42 </if> 43 <if test="account != null"> 44 ACCOUNT, 45 </if> 46 <if test="name != null"> 47 NAME, 48 </if> 49 <if test="password != null"> 50 PASSWORD, 51 </if> 52 <if test="roleId != null"> 53 ROLE_ID, 54 </if> 55 </trim> 56 <trim prefix="values (" suffix=")" suffixOverrides=","> 57 <if test="id != null"> 58 #{id,jdbcType=INTEGER}, 59 </if> 60 <if test="account != null"> 61 #{account,jdbcType=VARCHAR}, 62 </if> 63 <if test="name != null"> 64 #{name,jdbcType=VARCHAR}, 65 </if> 66 <if test="password != null"> 67 #{password,jdbcType=VARCHAR}, 68 </if> 69 <if test="roleId != null"> 70 #{roleId,jdbcType=INTEGER}, 71 </if> 72 </trim> 73 </insert> 74 <update id="updateByPrimaryKeySelective" parameterType="com.standard.model.User"> 75 update STANDARD_USER 76 <set> 77 <if test="account != null"> 78 ACCOUNT = #{account,jdbcType=VARCHAR}, 79 </if> 80 <if test="name != null"> 81 NAME = #{name,jdbcType=VARCHAR}, 82 </if> 83 <if test="password != null"> 84 PASSWORD = #{password,jdbcType=VARCHAR}, 85 </if> 86 <if test="role.id != null"> 87 ROLE_ID = #{roleId,jdbcType=INTEGER}, 88 </if> 89 </set> 90 where ID = #{id,jdbcType=INTEGER} 91 </update> 92 <update id="updateByPrimaryKey" parameterType="com.standard.model.User"> 93 update STANDARD_USER 94 set ACCOUNT = #{account,jdbcType=VARCHAR}, 95 NAME = #{name,jdbcType=VARCHAR}, 96 PASSWORD = #{password,jdbcType=VARCHAR}, 97 ROLE_ID = #{roleId,jdbcType=INTEGER} 98 where ID = #{id,jdbcType=INTEGER} 99 </update> 100 101 </mapper>
注意:
<?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">
可以同上边提到的mybatis-config.xml配置比较此部分内容,对小白理解mybatis或许会有帮助
五、最后测试一下
先展示一下POJO: User.java
public class User{ private Integer id; private String account; private String name; private String password; private Integer roleId; private Role role; public Integer getRoleId() { return this.roleId; } public void setRoleId(Integer roleId ) { this.roleId = roleId; } public Role getRole() { return this.role; } public void setRole(Role role ) { this.role = role; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }
然后写个测试类
public class UserTest { static SqlSession sqlSession=null; static UserMapper userMapper; public static void main(String[] args ) { try{ sqlSession=SqlSessionFactoryUtil.openSqlSession(); userMapper=sqlSession.getMapper(UserMapper.class); UserTest userTest=new UserTest(); //插入 int i =userTest.insert(); System.out.println(i); sqlSession2.commit(); }catch(Exception e){ System.err.println("---"+e.getMessage()); sqlSession.rollback(); }finally{ if(sqlSession!=null){ sqlSession.close(); } } } public int insert(){ User user=new User(); user.setId(9); user.setName("小白"); user.setAccount("admin"); user.setPassword("123456"); user.setRoleId(1); int i = userMapper.insert(user); return i; } }
最后就完成了一次插入数据库操作。
小白刚刚起步,欢迎吐槽~~