MyBatis进阶(一)

目录

MyBatis日志管理

MyBatis动态SQL

MyBatis的缓存

MyBatis的一级缓存

MyBatis的二级缓存

二级缓存的相关配置

MyBatis缓存查询的顺序

 MyBatis的逆向工程

创建逆向工程的步骤


MyBatis日志管理

  • 日志文件是用于记录系统操作事件的记录文件或文件集合
  • 日志保存历史数据,是诊断问题以及理解系统活动的重要依据

引入依赖

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

logback是允许日志进行自定义的,需要在resource目录下新建logback.xml文件

日志输出级别(优先级高到低):

  • error: 错误 - 系统的故障日志
  • warn: 警告 - 存在风险或使用不当的日志
  • info: 一般性消息
  • debug: 程序内部用于调试信息
  • trace: 程序运行的跟踪信息

appender:用来说明在什么地方进行日志的输出

pattern:用来规定日志输出的格式

  • [%thread]:所输出的线程名字

  • %d{HH:mm:ss.SSS}:时间精确到毫秒

  • %-5level:代表日志输出的级别,-5说明按照5个字符进行右对齐

  • %logger{36}:说明是哪个类产生的日志

  • %msg%:具体的日志内容

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
       <encoder>
           <pattern>[%thread] %d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
       </encoder>
   </appender>
    <root level="debug">
        <appender-ref ref="console"/>
    </root>
</configuration>

MyBatis动态SQL

        Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决 拼接SQL语句字符串时的痛点问题。

if:

        if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中 的内容不会执行。

<!--List<Emp> getEmpListByMoreTJ(Emp emp);-->
<select id="getEmpListByMoreTJ" resultType="Emp">
    select * from t_emp where 1=1
    <if test="ename != '' and ename != null">
        and ename = #{ename}
    </if>
    <if test="age != '' and age != null">
        and age = #{age}
    </if>
    <if test="sex != '' and sex != null">
        and sex = #{sex}
    </if>
</select>

where:        

        where标签会动态地对子sql进行判断,若第一个条件前面出现了and,则破坏了语法结构,他会把and给去掉,若有两个条件则第二个条件的and不会被去掉。

<select id="dynamicSQL" parameterType="java.util.Map" resultType="com.imooc.mybatis.entity.Goods">
        select * from t_goods
        <where>
          <if test="categoryId != null">
              and category_id = #{categoryId}
          </if>
          <if test="currentPrice != null">
              and current_price &lt; #{currentPrice}
          </if>
        </where>
</select>

where和if一般结合使用:

a>若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字 b>若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的 and去掉

注意:where标签不能去掉条件最后多余的and

trim:

若标签中有内容时:

        prefix | suffix:将trim标签中内容前面或后面添加指定内容
        suffixoverrides | prefixoverrides :将trim标签中内容前面或后面去掉指定内容

若标签中没有内容时,trim标签 也没有任何效果

<select id="getEmpListByMoreTJ" resultType="Emp">
	select * from t_emp
	<trim prefix="where" suffixOverrides="and">
		<if test="ename != '' and ename != null">
			ename = #{ename} and
		</if>
		<if test="age != '' and age != null">
			age = #{age} and
		</if>
		<if test="sex != '' and sex != null">
			sex = #{sex}
		</if>
	</trim>
</select>

choose、when、otherwise:

choose、when、otherwise相当于if...else if..else

<!--List<Emp> getEmpListByChoose(Emp emp);-->
<select id="getEmpListByChoose" resultType="Emp">
	select <include refid="empColumns"></include> from t_emp
		<where>
			<choose>
				<when test="ename != '' and ename != null">
					ename = #{ename}
				</when>
				<when test="age != '' and age != null">
					age = #{age}
				</when>
				<when test="sex != '' and sex != null">
					sex = #{sex}
				</when>
				<when test="email != '' and email != null">
					email = #{email}
				</when>
    			<otherwise>
        			did = 1
    			</otherwise>
			</choose>
		</where>
</select>

foreach:

属性:

  • collection:设置要循环的数组或集合
  • item:表示集合或数组中的每一个数据
  • separator:设置循环体之间的分隔符
  • open:设置foreach标签中的内容的开始符
  • close:设置foreach标签中的内容的结束符

批量增加和删除:

<!--int insertMoreEmp(@Prarm("emps")List<Emp> emps);-->
<insert id="insertMoreEmp">
	insert into t_emp values
	<foreach collection="emps" item="emp" separator=",">
		(null,#{emp.ename},#{emp.age},#{emp.sex},#{emp.email},null)
	</foreach>
</insert>

<!--int deleteMoreByArray(@Prarm("eids")int[] eids);-->
<delete id="deleteMoreByArray">
	delete from t_emp where
	<foreach collection="eids" item="eid" separator="or">
		eid = #{eid}
	</foreach>
</delete>

<!--int deleteMoreByArray(@Prarm("eids")int[] eids);-->
	<delete id="deleteMoreByArray">
		delete from t_emp where eid in
        <!--sql语句中in后要加括号-->
		<foreach collection="eids" item="eid" separator="," open="(" close=")">
			#{eid}
		</foreach>
</delete>

sql片段

sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入。

设置SQL片段: <sql id= "empColumns">eid, emp_ name , age, sex, email</sql>
引用SQL片段: <include refid="empColumns"></include>

<sql id="empColumns">
    eid,ename,age,sex,did
</sql>

<!--在SQL语句中-->
select <include refid="empColumns"></include> from t_emp

MyBatis的缓存

MyBatis的一级缓存

       MyBatis的一级缓存是默认开启的,一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就 会从缓存中直接获取,不会从数据库重新访问。

@Test
public vold testCache(){
    sqlSession sq1session sqlSessionUtils.getsqlSession(); 
    CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
    Emp emp1 = mapper.getEmpByEid(1);
    system.out.print1n(emp1);
    Emp emp2 = mapper.getEmpByEid(1);
    system.out.println(emp2);
}

         日志信息中只输出了一个SQL,当第二次调用getEmpByEid(1)方法执行查询的时候,没有去执行SQL,而是从缓存中获取数据。

 MyBatis的二级缓存

        二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被 缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取。

二级缓存并非默认开启,其开启的条件:

  • 在核心配置文件中,设置全局配置属性cacheEnabled="true",默认为true,不需要设置。

  • 在映射文件中设置标签。

  • 二级缓存必须在SqlSession关闭或提交之后有效。

  • 查询的数据所转换的实体类类型必须实现序列化的接口

    eg:public class Emp implements Serializable {}

        在我们没有关闭或提交sqlSession,我们查询的数据会被保存到一级缓存当中;在我们关闭或者提交sqlSession的时候,这个数据才会被保存到二级缓存当中。

使二级缓存失效的情况: 两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效。

@Test
public void testTwoCache(){
    try {
        Inputstream is = Resources.getResourceAsstream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
        CacheMapper mapper = sqlSession1.getMapper(CacheMapper.class);
        System.out.println(mapper.getEmpByEid(1));
        sqlSession1.close();
        SqlSession sqlSession2 = sqlSessionFactory.openSession(autoCommit: true);
        CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
        System.out.println(mapper IgetEmpByEid(1));
        sqlSession2.close();
    } catch(IOException e){
        e.printStackTrace();
    }
}

注意不能再引用工具类,每引用一次工具类就会重新创建一个SqlSessionFactory。

 二级缓存的相关配置

 <!--开启了二级缓存
        eviction是缓存的清除策略,当缓存对象数量达到上限后,自动触发对应算法对缓存对象清除
            1.LRU – 最近最久未使用:移除最长时间不被使用的对象。
            O1 O2 O3 O4 .. O512
            14 99 83 1     893
            2.FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
            3.SOFT – 软引用:移除基于垃圾收集器状态和软引用规则的对象。
            4.WEAK – 弱引用:更积极的移除基于垃圾收集器状态和弱引用规则的对象。
-->
    <cache eviction="LRU" flushInterval="600000" size="512" readOnly="true"/>

MyBatis缓存查询的顺序

 MyBatis的逆向工程

创建逆向工程的步骤

1.添加依赖和插件

    <!-- 依赖MyBatis核心包 -->
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
    </dependencies>
    <!-- 控制Maven在构建过程中相关配置 -->
    <build>
        <!-- 构建过程中用到的插件 -->
        <plugins>
            <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.0</version>
                <!-- 插件的依赖 -->
                <dependencies>
                    <!-- 逆向工程的核心依赖 -->
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                    <!-- 数据库连接池 -->
                    <dependency>
                        <groupId>com.mchange</groupId>
                        <artifactId>c3p0</artifactId>
                        <version>0.9.2</version>
                    </dependency>
                    <!-- MySQL驱动 -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.8</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

2.创建MyBatis的核心配置文件 mybatis-config.xml

3.创建逆向工程的配置文件

文件名必须是:generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--
    targetRuntime: 执行生成的逆向工程的版本
    MyBatis3Simple: 生成基本的CRUD五种方法(清新简洁版)
    MyBatis3: 生成带条件的CRUD(奢华尊享版)
    -->
    <context id="DB2Tables" targetRuntime="MyBatis3Simple">
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis"
                        userId="root"
                        password="123456">
        </jdbcConnection>
        <!-- javaBean的生成策略-->
        <javaModelGenerator targetPackage="com.atguigu.mybatis.bean"
                            targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- SQL映射文件的生成策略 -->
        <sqlMapGenerator targetPackage="com.atguigu.mybatis.mapper"
                         targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- Mapper接口的生成策略 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.atguigu.mybatis.mapper" 
                             targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 逆向分析的表 -->
        <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
        <!-- domainObjectName属性指定生成出来的实体类的类名 -->
        <table tableName="t_emp" domainObjectName="Emp"/>
        <table tableName="t_dept" domainObjectName="Dept"/>
    </context>
</generatorConfiguration>

4.执行MBG插件的generate目标

双击即可

​​​​​​​

QBC查询

    @Test
    public void testMBG() throws IOException {
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSession sqlSession = new
                SqlSessionFactoryBuilder().build(is).openSession(true);
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        EmpExample empExample = new EmpExample();
        //创建条件对象,通过andXXX方法为SQL添加查询添加,每个条件之间是and关系
        empExample.createCriteria().andEnameLike("a").andAgeGreaterThan(20).andDidIsNotNull();
        //将之前添加的条件通过or拼接其他条件
        empExample.or().andSexEqualTo("男");
        List<Emp> list = mapper.selectByExample(empExample);
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值