框架

MyBatis

2017-10-11  本文已影响0人  AntiGravity

一、理解

概念:一个持久层框架
作用:ORM将sql语句映射成实体类
特点:

原理图

二、配置

官方文档地址:http://www.mybatis.org/mybatis-3/zh/

1. maven依赖

org.mybatis - mybatis

2. xml配置文件

<?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 resource="db.properties" /><!--在整个配置文件中使用来替换需要动态配置的属性值-->
    <settings>
        <setting name="autoMappingBehavior" value="FULL"/><!--自动映射任意复杂的结果集(无论是否嵌套)-->
        <setting name="mapUnderscoreToCamelCase" value="true"/><!--开启自动驼峰命名规则映射-->
    </settings>
    <typeAliases><!--设置别名——使用时不必写完整reference路径,只需写别名-->
        <!-- 指定包下面的所有实体类都会将类名作为别名 -->
        <package name="com.maven01.bean"></package>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.classDriver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers><!--配置SQL映射文件-->
        <mapper resource="UserMapper.xml"/>
        <mapper resource="GoodsMapper.xml"/>
    </mappers>
</configuration>

3. Mapper的xml配置文件

先了解一下resultMap

作用:
1、可以将表字段与javabean对象属性名进行映射
2、将映射抽取出来,可以给多个statement所使用

映射的原理:
1、先拿到type指定的类的class
2、通过newInstance创建对象
3、获取property中属性名,通过反射的方式调用对应的set()方法
4、调用方法的invoke()方法,将column的值赋值进去
5、返回封装好的对象

静态sql语句的写法
<mapper namespace="接口全限定名">
    <select id="抽象函数" resultMap="返回结果id">
        select * from goods where gid=3
    </select>
    <!--关联resultMap嵌套-->
    <resultMap id="返回结果id" type="返回类型">
    <!-- 建议主键写上,可以提高mybatis的效率 -->
    <id property="属性" column="字段"/>
    <!--关联resultMap和resultMap-->
    <association property="属性" column="要传递的字段(传递后消失)" resultMap="被关联的resultMap id"/>
    <!--关联resultMap和select语句-->
    <resultMap id="goodsResultMap" type="Goods">
        <id property="主键对应的属性" column="主键"/><!--property对应类的变量,column对应表的列名-->
        <association property="属性" select="select语句全限定名" column="字段" javaType="关联的pojo类型"/>
    </resultMap>
</mapper>
动态sql语句
<if test="判断条件"></if>
<!--注意:1、字符串的拼接建议使用concat来代替${}
2、判断条件中获取数据不用加#{},与el表达式不一样-->
    <where><!--自动去除第一个and-->
      <if test="判断">条件</if>
      <if test="判断">and 条件</if>
    </where>
<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM BLOG WHERE state = 'ACTIVE'
  <choose><!--相当于switch case default-->
    <when test="判断">AND title like #{title}</when>
    <otherwise>AND featured = 1</otherwise>
  </choose>
</select>
 select * from good
    <trim prefix="where" prefixOverrides="and|or">
      <!--添加where在前面,并且去除第一个and-->
      <if test="判断">and 条件</if>
      <if test="判断">and 条件</if>
    </trim>
  1. open代表在集合前面添加的字符串
  2. close代表在集合后面添加的字符串
  3. separator代表集合分割使用的字符串
  4. collection代表被循环的集合,值可以是list、map、array
  5. 常见用法,in的语句
<select id="selectGoodByGid" parameterType="list" resultType="Good">
    select * from good
    <where>id in
      <foreach item="item" collection="list" open="(" separator="," close=")">
             #{item}
        </foreach>
    </where>
  </select>

三、使用

测试

public class GoodsMapperTest extends TestCase {
    SqlSession session=null;
    @Before
    public void setUp() throws Exception {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {//获取配置文件的流
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //根据流建立工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        session = factory.openSession();//根据工厂获得session
    }
    public void testSelectGoodsById(){
      //由session取得mapper接口
        GoodsMapper mapper = session.getMapper(GoodsMapper.class);
        Goods goods = mapper.selectGoodsById();//调用sql语句
        System.out.println(goods);
    }
    @After
    public void tearDown() throws Exception {
        session.close();
    }
}

缓存

一级缓存

同一个SqlSession,执行相同的sql语句,先找缓存
默认开启

二级缓存

同一个namespace下的不同的SqlSession,执行相同的sql语句,先找缓存

配置

1、setting中设置cacheEnabled="true"
2、mapper中添加标签
3、statement中添加useCache="true"
4、对需要缓存的对象需要序列化
5、调用session.close()时候才将数据写入二级缓存

原理

1、通过Jdk动态代理方式创建出Mapper接口的代理对象
2、有一个实现了InvocationHandler的MapperProxy类,可以获取被代理对象注解上的sql语句,或者获取对应xml文件中的sql语句,然后通过jdbc实现对数据库的增删改查操作

上一篇下一篇

猜你喜欢

热点阅读