Mybatis学习记录

一、MyBatis简介

在这里插入图片描述

1.1、MyBatis历史

MyBatis最初是Apache的一个开源项目iBatis,2010年6月这个项目由Apache Software Foundation迁移到了Google Code。随着开发团队转投Google Code旗下,iBatis3.x正式更名为MyBatis,代码于2013年11月迁移到Github

1.2、MyBatis特性
  • MyBatis是支持定制化SQL存储过程以及高级映射的优秀的持久层框架。
  • MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。
  • MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和javaPOJO(Plan Old java Objects, 普通的java对象)映射成数据库中的记录。
  • MyBatis是一个半自动的ORM(Object Relation Mapping)框架
1.3、MyBatis下载

下载地址:添加链接描述

1.4、和其他持久化层技术对比
  • JDBC
    • SQL夹杂在java代码中耦合度较高,导致硬编码内伤。
    • 维护不易且实际开发需求中SQL有变化,频繁修改的情况多见。
    • 代码冗长,开发效率低
  • Hibernate 和 JPA
    • 操作简便,开发效率高
    • 程序中的长难复杂SQL需要绕过框架
    • 内部自动生产的SQL,不容易做特殊优化
    • 基于全映射的全自动框架,大量字段的POJO进行部分映射时比较困难
    • 反射操作太多,导致数据库性能下降
  • MyBatis
    • 轻量级,性能出色
    • SQL和Java编码分开,功能边界清晰。Java代码专注业务、SQL语句专注数据
    • 开发效率稍逊于Hibernate,但是完全能够接受

二、MyBatis框架搭建

2.1、加入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cjw.Mybatis_demo1</groupId>
    <artifactId>Mybatis_demo1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <packaging>jar</packaging>
   <dependencies>
       <!--MyBatis核心-->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.5.7</version>
       </dependency>
       <!--junit测试-->
       <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.12</version>
       </dependency>
        <!--mysql驱动-->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.3</version>
       </dependency>
<!--       log4j日志-->
       <dependency>
           <groupId>log4j</groupId>
           <artifactId>log4j</artifactId>
           <version>1.2.17</version>
       </dependency>
   </dependencies>
</project>

2.2、创建MyBatis的核心配置文件

习惯上命名为mybatis-config.xml,这个文件名仅仅只是建议,并非强制要求。将来整合Spring之后,这个配置文件可以省略。

  • 核心配置文件主要用于配置链接数据库的环境以及MyBatis的全局配置信息
  • 核心配置文件存放的位置是src/main/resources目录下
<?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>
<!--    引入jdbc.properties配置文件-->
    <properties resource="jdbc.properties"></properties>
    <settings>
        <setting name="cacheEnabled" value="false"/>
        <setting name="lazyLoadingEnabled" value="false"/>
        <setting name="multipleResultSetsEnabled" value="false"/>
        <setting name="useColumnLabel" value="false"/>
        <setting name="useGeneratedKeys" value="false"/>
        <setting name="autoMappingBehavior" value="PARTIAL"/>
        <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <setting name="defaultStatementTimeout" value="25"/>
        <setting name="defaultFetchSize" value="100"/>
        <setting name="safeRowBoundsEnabled" value="false"/>
        <setting name="mapUnderscoreToCamelCase" value="false"/> <!--开启驼峰命名法-->
        <setting name="localCacheScope" value="SESSION"/>
        <setting name="jdbcTypeForNull" value="OTHER"/>
        <setting name="lazyLoadTriggerMethods"
                 value="equals,clone,hashCode,toString"/>
    </settings>
    <!--
            类型别名 不区别大小写
            不写alias 默认为类名
    -->
    <typeAliases>
        <typeAlias type="com.cjw.mybatis.pojo.User" alias="user"></typeAlias>
    <!--        以包为单位,将包下所有的类型设置默认的类型别名,即类名不区分大小 常用-->
        <package name="com.cjw.mybatis.pojo"/>
    </typeAliases>
    <!--    配置数据库环境-->
    <environments default="development">
        <environment id="development">
            <!--            事务管理方式-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--                设置连接数据库的驱动-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射文件-->
    <mappers>
        <!--单个文件-->
    <!--        <mapper resource="mappers/UserMapper.xml"/>-->
    <!--
        以包来引入文件
        1、mapper接口所在的包要和映射文件所在的包一致
        2、mapper接口和映射文件一致
        org.apache.ibatis.binding.BindingException:
        Type interface com.cjw.mybatis.dao.UserMapper is not known to the MapperRegistry.
    -->
        <package name="com.cjw.mybatis.dao" />
    </mappers>
</configuration>
2.3、创建Mapper接口

MyBatis中的mapper接口相当于以前的Dao,但是区别在于,mapper仅仅是接口,我们不需要提供实现类。例如UserMapper示例

public interface UserMapper {
    int insertUser(User user);
    int deleteUser(User user);
    int udpateUser(User user);
    List<User> selectUser(User user);
    List<User> selectUserByParams(@Param("userName") String userName, @Param("userAddress") String userAddress);
    User selectUserById(@Param("userId") String userId);
}

2.4、 创建MyBatis的映射文件
  • 映射文件的命名规则:
    表所对应的实体类的类名+Mapper.xml
    例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml。因此一个映射文件对应一个实体类,对应一张表的操作
    MyBatis映射文件用于编写SQL,访问以及操作表中的数据
    MyBatis映射文件存放的位置是src/main/resouces/mappers目录下
  • MyBatis中可以面向接口操作数据,要保证两个一致:
    • mapper接口的全类名和映射文件的命令空间(namespace)保持一致
    • mapper接口中的方法的方法名和映射文件中编写的ID保持一致
<?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="com.cjw.mybatis.dao.UserMapper">
    <insert id="insertUser" parameterType="com.cjw.mybatis.pojo.User">
        insert into user
        value(null, #{userName}, #{userAge}, #{userAddress}, #{userRole})
    </insert>
    <delete id="deleteUser" parameterType="user">
        delete from user
        where userId = #{userId}
    </delete>
    <update id="udpateUser" parameterType="user">
        update user
        <set>
            <if test="userName != null">
                userName = #{userName},
            </if>
            <if test="userAddress != null">
                userAddress = #{userAddress},
            </if>
        </set>
        where userId = #{userId}
    </update>
    <select id="selectUser" resultType="user" parameterType="user">
    select * from user
    <where>
        <if test="userName != null">and userName like concat('%',#{userName},'%')</if>
        <if test="userAddress != null">and userAddress like concat('%',#{userAddress},'%')</if>
    </where>
</select>

    <select id="selectUserByParams" resultType="user">
        select * from user
        <where>
            <if test="userName != null">and userName like concat('%',#{userName},'%')</if>
            <if test="userAddress != null">and userAddress like concat('%',#{userAddress},'%')</if>
        </where>
    </select>

    <select id="selectUserById" resultType="user">
        select * from user where userId = #{userId}
    </select>
</mapper>

2.5、 测试环境
  • SqlSession:代表java程序和“数据库”之间的“会话”。(HttpSession是java程序和浏览器之间的会话)
  • SqlSessionFactory:是生产SqlSession的工厂
  • 工厂模式:如果创建某一个对象,使用的过程基本固定,那么我们就可以把创建这个对象的相关代码封装到一个“工厂类”中,以后都使用这个工厂类来“生产”我们需要的对象。
public class MyBatisUser {
    @Test
    public void testUser() {
        try {
            //读取配置文件
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            //根据配置文件参数构建SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //通过SqlSessionFactory获取SqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //通过SqlSession读取UserMapper
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.selectUserById(String.valueOf(1));
            System.out.println("user = " + user);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.6、 加入Log4j日志功能
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <!--控制台输出sql执行过程-->
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}: %m%n" />
        </layout>
    </appender>

    <logger name = "java.sql">
        <level value = "debug"/>
    </logger>

    <logger name="org.apache.ibatis">
        <level value="info" />
    </logger>

    <root>
        <level value="debug"></level>
        <appender-ref ref="STDOUT"/>
    </root>
</log4j:configuration>

三、核心配置文件详解

  • 配置文件中的标签遵循以下顺序:
The content of element type "configuration" must match "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)".
  • 标签简介
    在这里插入图片描述

    • properties标签
      可以引入properties配置文件来配置数据连接信息
      数据库属性的加载顺序一般是
      1. 首先读取Properties元素体中指定的属性
      2. classpath资源Properties元素url属性加载的属性被秒读,并覆盖任何已经指定的重复属性。
      3. 作为方法参数传递的属性最后读取,并覆盖任何重复的属性
        在这里插入图片描述
    • settings
    	    <settings>
        <!--    全局启用或禁用在此配置下的任何映射器中配置的任何缓存 -->
        <setting name="cacheEnabled" value="false"/>
        <!--   全局启用或禁用延迟加载。启用后,所有关系都将被惰性加载。对于特定的关系,可以使用fetchType属性替换该值。     -->
        <setting name="lazyLoadingEnabled" value="false"/>
        <!--允许或禁止从一条语句返回多个resultset(需要兼容的驱动程序)-->
        <setting name="multipleResultSetsEnabled" value="false"/>
        <setting name="useColumnLabel" value="false"/>
        <!--
                允许JDBC支持生成的键。需要兼容的驱动程序。如果设置为true,此设置将强制使用生成的密钥,
                因为一些驱动程序拒绝兼容性,但仍然可以工作(例如Derby)-->
        <setting name="useGeneratedKeys" value="false"/>
        <!--
            指定MyBatis是否以及如何自动将列映射到字段/属性。
            NONE关闭自动映射功能。
            PARTIAL将只自动映射内部没有定义嵌套结果映射的结果。
            FULL将自动映射任何复杂度的结果映射(包含嵌套或其他)-->
        <setting name="autoMappingBehavior" value="PARTIAL"/>
        <!--
           指定当检测到自动映射目标的未知列(或未知属性类型)时的行为。
           -->
        <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <!--   设置驱动程序等待数据库响应的秒数。     -->
        <setting name="defaultStatementTimeout" value="25"/>
        <!--
            为驱动程序设置一个提示,以控制返回结果的抓取大小。
            此参数值可由查询设置覆盖
        -->
        <setting name="defaultFetchSize" value="100"/>
        <!--允许在嵌套语句上使用RowBounds。如果允许,设置为false-->
        <setting name="safeRowBoundsEnabled" value="false"/>
        <!--启用从经典数据库列名的自动映射A_COLUMN来驼驼形的经典Java属性名aColumn-->
        <setting name="mapUnderscoreToCamelCase" value="false"/> <!--开启驼峰命名法-->
        <!--
        MyBatis使用本地缓存来防止循环引用和加速重复的嵌套查询。
        默认情况下(SESSION)在会话期间执行的所有查询都被缓存。
        如果localCacheScope=STATEMENT本地会话仅用于语句执行,则在对同一会话的两个不同调用之间不会共享数据
        SqlSession
        -->
        <setting name="localCacheScope" value="SESSION"/>
        <!--
        当没有为参数提供特定的JDBC类型时,为空值指定JDBC类型。一些驱动程序需要指定列JDBC类型,
        但其他驱动程序使用泛型值,如NULLVARCHAROTHER
        -->
        <setting name="jdbcTypeForNull" value="OTHER"/>
        <!--指定哪个对象的方法触发延迟加载-->
        <setting name="lazyLoadTriggerMethods"  value="equals,clone,hashCode,toString"/>
    </settings>
    
    • environments
	    <!--    配置数据库环境-->
    <environments default="development">
        <environment id="development">
            <!--
                事务管理方式
                属性:
                 type="JDBC|MANAGED"
                 JDBC:表示当前环境中,执行SQL时,使用的JDBC中原生的事务
                 管理方式,事务的提交或会话需要手动处理
            -->
            <transactionManager type="JDBC"/>
            <!--    
            dataSource:配置数据源
                属性:
                    type: 设置数据源的类型
                    type="POOLED|UNPOOLED|JNDI"
                    POOLED: 表示使用数据库连接池缓存数据库连接
                    UNPOOLED: 表示不使用数据库连接池
                    JNDI: 表示使用上下文中的数据源
            -->
            <dataSource type="POOLED">
                <!--                设置连接数据库的驱动-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>

四、MyBatis的增删改查

参考UerMapper和UserMapper.xml示例

  • UserMapper
public interface UserMapper {
    int insertUser(User user);
    int deleteUser(User user);
    int udpateUser(User user);
    List<User> selectUser(User user);
    List<User> selectUserByParams(@Param("userName") String userName, @Param("userAddress") String userAddress);
    User selectUserById(@Param("userId") String userId);
}
  • UserMapper.xml
<mapper namespace="com.cjw.mybatis.dao.UserMapper">
    <insert id="insertUser" parameterType="com.cjw.mybatis.pojo.User">
        insert into user
        value(null, #{userName}, #{userAge}, #{userAddress}, #{userRole})
    </insert>
    <delete id="deleteUser" parameterType="user">
        delete from user
        where userId = #{userId}
    </delete>
    <update id="udpateUser" parameterType="user">
        update user
        <set>
            <if test="userName != null">
                userName = #{userName},
            </if>
            <if test="userAddress != null">
                userAddress = #{userAddress},
            </if>
        </set>
        where userId = #{userId}
    </update>
    <select id="selectUser" resultType="user" parameterType="user">
    select * from user
    <where>
        <if test="userName != null">and userName like concat('%',#{userName},'%')</if>
        <if test="userAddress != null">and userAddress like concat('%',#{userAddress},'%')</if>
    </where>
</select>

    <select id="selectUserByParams" resultType="user">
        select * from user
        <where>
            <if test="userName != null">and userName like concat('%',#{userName},'%')</if>
            <if test="userAddress != null">and userAddress like concat('%',#{userAddress},'%')</if>
        </where>
    </select>

    <select id="selectUserById" resultType="user">
        select * from user where userId = #{userId}
    </select>
</mapper>
  • 测试类
    /**
     * 增、删、改
     */
    @Test
 public void testUsetMapperAutoCommit () {
        //加载核心配置文件 获取sqlSession
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //获取SqlSessionBuilder
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            //获取sqlSessionFactory
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
            //获取SqlSession
            //openSession(boolean autoCommit) 默认不自动提交事务
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //获取Mapper
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);//代理模式
            //insert数据
            User user = new User();
            user.setUserAddress("哈哈");
            user.setUserAge(12);
            user.setUserName("测试");
            int insertResult = mapper.insertUser(user);
            System.out.println("insertResult = " + insertResult);
            //sqlSession.commit(); // <transactionManager type="JDBC"/> 需要手动提交
            //update数据
            User userUpdate = new User();
            userUpdate.setUserAddress("哈哈测试");
            userUpdate.setUserAge(12);
            userUpdate.setUserName("测试姓名");
            userUpdate.setUserId(2);
            int updateResult = mapper.udpateUser(userUpdate);
            System.out.println("updateResult = " + updateResult);
            //delete数据
            User userDelete = new User();
            userDelete.setUserId(3);
            int deleteResult = mapper.deleteUser(userDelete);
            System.out.println("deleteResult = " + deleteResult);
            //select数据
            User userSelect = new User();
            userSelect.setUserName("测试");
            List<User> selectResult = mapper.selectUser(userSelect);
            selectResult.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

五、MyBatis获取参数值的两种方式(重点)

MyBatis获取参数值的两种方式:${} 和 #{}
${}的本质就是字符串拼接,#{}的本质就是占位符赋值
${}使用字符串拼接的方式拼接sql, 若为字符串类型或日期类型进行赋值时,需要手动添加单引号;但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号。

5.1、单个字面量类型的参数

mapper接口中的方法参数为单个的字面量类型
此时可以使用${}#{}以任意的名称获取参数的值,注意${}需要手动添加单引号。

5.2、多个字面量类型的参数

mapper接口中的方法参数为多个时,此时MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1...为键,以参数为值;因此只需要通过${} 和#{}访问map集合的键就可以获取相应的值,注意 ${} 需要手动添加单引号。

5.3、map集合类型的参数

mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中只需要通过${} 和#{} 访问map集合的键就可以获取相对应的值, ${} 需要手动添加单引号。

5.4、实体类类型的参数(重点)

mapper接口中的方法参数为实体类对象时
此时可以使用${} 和 #{},通过访问实体类对象中的属性名获取属性值,注意 ${}需要手动添加单引号。

5.5、使用@Param标识参数(重点)

可以通过@Param注解标识mapper接口中的方法参数
此时,会将这些参数放在map集合,以@Param注解的value属性值为键,以参数为值;以param1,param2...为键,以参数为值;只需要通过${} 和 #{}访问map集合的键就可以获取相对应的值,注意 ${} 需要手动添加单引号。

六、MyBatis的各种查询功能

  • 如果查询出的数据只有一条,可以通过
    1. 实体类对象接收
    2. List集合接收
    3. Map集合接收,结果{password=123456, sex=男, id=1, age=23, username=admin}
  • 如果查询出的数据有多条,一定不能用实体类对象接收,会抛异常TooManyResultsException,可以通过
    1. 实体类类型的LIst集合接收
    2. Map类型的LIst集合接收
    3. mapper接口的方法上添加@MapKey注解(@MapKey 当返回多条map数据时,指定键;否则就是一个属性一个值)
6.1、查询一个实体类对象
/**
 * 根据用户id查询用户信息
 * @param id
 * @return
 */
User getUserById(@Param("id") int id);
<!--User getUserById(@Param("id") int id);-->
<select id="getUserById" resultType="User">
	select * from t_user where id = #{id}
	</select>
6.2、查询一个List集合
/**
 * 查询所有用户信息
 * @return
 */
List<User> getUserList();

<!--List<User> getUserList();-->
<select id="getUserList" resultType="User">
	select * from t_user
</select>
6.3、查询单个数据
查询用户的总记录数  
@returnMyBatis中,对于Java中常用的类型都设置了类型别名  
例如:java.lang.Integer-->int|integer  
例如:int-->_int|_integer  
例如:Map-->map,List-->list  
  
int getCount();

<!--int getCount();-->
<select id="getCount" resultType="_integer">
	select count(id) from t_user
</select>
6.4、查询一条数据为map集合
/**  
 * 根据用户id查询用户信息为map集合  
 * @param id  
 * @return  
 */  
Map<String, Object> getUserToMap(@Param("id") int id);


<!--Map<String, Object> getUserToMap(@Param("id") int id);-->
<select id="getUserToMap" resultType="map">
	select * from t_user where id = #{id}
</select>
<!--结果:{password=123456, sex=, id=1, age=23, username=admin}-->
6.5、查询多条数据为map集合

count(1) 和count(*) 是没有区别的, 但是count(字段)是将空值去除的。

  • 第一种
    将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取
/**  
 * 查询所有用户信息为map集合  
 * @return  
 * 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取  
 */  
List<Map<String, Object>> getAllUserToMap();

<!--Map<String, Object> getAllUserToMap();-->  
<select id="getAllUserToMap" resultType="map">  
	select * from t_user  
</select>
<!--
	结果:
	[{password=123456, sex=, id=1, age=23, username=admin},
	{password=123456, sex=, id=2, age=23, username=张三},
	{password=123456, sex=, id=3, age=23, username=张三}]
-->
  • 第二种
    将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的map集合。
/**
 * 查询所有用户信息为map集合
 * @return
 * 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的map集合
 */
@MapKey("id")
Map<String, Object> getAllUserToMap();

<!--Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">
	select * from t_user
</select>
<!--
	结果:
	{
		1={password=123456, sex=, id=1, age=23, username=admin},
		2={password=123456, sex=, id=2, age=23, username=张三},
		3={password=123456, sex=, id=3, age=23, username=张三}
	}
-->
6.6、@MapKey注解
public interface SelectMapper {
    /**
     * 这是一个在返回值为Map的方法上的注解。它能够将存放对象的List转化为key值为对象
     * 的某一属性的Map。属性有value,填入的是对象的属性名,作为Map的key值
     * *******唯一的字段
     * @return
     */
   @MapKey("userId")
    Map<String, Object> getUserByIdToMap1() ;
  • 使用@MapKey注解结果
Maps = {1={userAddress=2222, userName=hh, userRole=1, userId=1, userAge=456}, 
  2={userAddress=哈哈测试, userName=测试姓名, userId=2, userAge=12},
   4={userAddress=哈哈, userName=测试, userId=4, userAge=12}, 
   5={userAddress=哈哈, userName=测试, userId=5, userAge=12}, 
   6={userAddress=哈哈, userName=测试, userId=6, userAge=12}, 
   7={userAddress=哈哈, userName=测试, userId=7, userAge=12},
    8={userAddress=哈哈, userName=测试, userId=8, userAge=12}, 9={userAddress=哈哈, userName=测试, userId=9, userAge=12},
     10={userAddress=哈哈, userName=测试, userId=10, userAge=12}, 11={userAddress=哈哈, userName=测试, userId=11, userAge=12},
      12={userAddress=哈哈, userName=测试, userId=12, userAge=12}, 13={userAddress=哈哈, userName=测试, userId=13, userAge=12}, 
      14={userAddress=哈哈, userName=测试, userId=14, userAge=12}, 15={userAddress=哈哈, userName=测试, userId=15, userAge=12}}
  • 不使用@MapKey注解
        [11/01/23 10:15:30:030 CST] DEBUG SelectMapper.getUserByIdToMap: ==>  Preparing: select * from user where userId = ?
            [11/01/23 10:15:30:030 CST] DEBUG SelectMapper.getUserByIdToMap: ==> Parameters: 2(Integer)
            [11/01/23 10:15:30:030 CST] DEBUG SelectMapper.getUserByIdToMap: <==      Total: 1
    Maps2 = {userAddress=哈哈测试, userName=测试姓名, userId=2, userAge=12}*/
}

七、特殊SQL的执行

  1. 模糊查询
<select id="getUserByLike" resultType="user">
    select * from user
    <!-- like '%#{userName}%' 会被解析成 '%?%' 就不会被解析成占位符
     1. like '%${userName}%'
     2. like concat('%', #{userName}, '%')
     3. like "%"#{userName}"%"
    -->
    where userName like "%"#{userName}"%"
</select>

  1. 批量删除
    只能使用${},如果使用#{},则解析后的sql语句为delete from t_user where id in ('1,2,3'),这样是将1,2,3看做是一个整体,只有id为1,2,3的数据会被删除。正确的语句应该是delete from t_user where id in (1,2,3),或者delete from t_user where id in ('1','2','3')
/**
 * 根据id批量删除
 * @param ids 
 * @return int
 * @date 2022/2/26 22:06
 */
int deleteMore(@Param("ids") String ids);

<delete id="deleteMore">
	delete from t_user where id in (${ids})
</delete>
//测试类
@Test
public void deleteMore() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
	int result = mapper.deleteMore("1,2,3,8");
	System.out.println(result);
}
  1. 动态设置表名
  • 只能使用${},因为表名不能加单引号
/**
 * 查询指定表中的数据
 * @param tableName 
 * @return java.util.List<com.atguigu.mybatis.pojo.User>
 * @date 2022/2/27 14:41
 */
List<User> getUserByTable(@Param("tableName") String tableName);

<!--List<User> getUserByTable(@Param("tableName") String tableName);-->
<select id="getUserByTable" resultType="User">
	select * from ${tableName}
</select>
  1. 添加功能获取自增的主键
<!--void insertUser(User user);-->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
	insert into t_user values (null,#{username},#{password},#{age},#{sex},#{email})
</insert>

八、自定义映射resultMap

8.1、resultMap处理字段和属性的映射关系
  • resultMap:设置自定义映射
    • 属性
      • id:表示自定义映射的唯一标识,不能重复
      • type:查询的数据要映射的实体类的类型
    • 子标签
      • id:设置主键的映射关系
      • result:设置普通字段的映射关系
    • 子标签属性
      • property:设置映射关系中实体类中的属性名
      • column:设置映射关系中表中的字段名
  • 若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射,即使字段名和属性名一致的属性也要映射,也就是全部属性都要列出来
<resultMap id="empResultMap" type="Emp">
	<id property="eid" column="eid"></id>
	<result property="empName" column="emp_name"></result>
	<result property="age" column="age"></result>
	<result property="sex" column="sex"></result>
	<result property="email" column="email"></result>
</resultMap>
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultMap="empResultMap">
	select * from t_emp
</select>
  • 若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性名符合Java的规则(使用驼峰)。此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系

    1. 可以通过为字段起别名的方式,保证和实体类中的属性名保持一致
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultType="Emp">
	select eid,emp_name empName,age,sex,email from t_emp
</select>
  1. 可以在MyBatis的核心配置文件中的setting标签中,设置一个全局配置信息mapUnderscoreToCamelCase,可以在查询表中数据时,自动将_类型的字段名转换为驼峰,例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为userName。核心配置文件详解
<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
8.2、处理多对一映射

查询书籍信息及书籍的拥有者

  • 级联赋值 (用户信息也用result 来接收其属性值)
    <resultMap id="empResultMapByUser" type="com.cjw.mybatis.pojo.Book">
        <id property="bkId" column="bkId"></id>
        <result property="bkName" column="bkName"></result>
        <result property="bktype" column="bktype"></result>
        <result property="bkNum" column="bkNum"></result>
        <result property="bkCounty" column="bkCounty"></result>
        <result property="bkAuthor" column="bkAuthor"></result>
        <result property="bkCb" column="bkCb"></result>
        <result property="empName" column="emp_name"></result>
        <result property="user.userId" column="userId"></result>
        <result property="user.userName" column="userName"></result>
    </resultMap>
    
     <select id="getAllBookByUserAndSelect1" resultMap="empResultMapByUser">
         select * from book
     </select>
  • association进行多对一映射
    嵌套结果和嵌套查询
  1. 嵌套结果
    <!--嵌套结果-->
    <resultMap id="empResultMapByUser2" type="com.cjw.mybatis.pojo.Book">
        <id property="bkId" column="bkId"></id>
        <result property="bkName" column="bkName"></result>
        <result property="bktype" column="bktype"></result>
        <result property="bkNum" column="bkNum"></result>
        <result property="bkCounty" column="bkCounty"></result>
        <result property="bkAuthor" column="bkAuthor"></result>
        <result property="bkCb" column="bkCb"></result>
        <result property="empName" column="emp_name"></result>
        <association property="user" javaType="User">
            <id property="userId" column="userId"></id>
            <result property="userName" column="userName"></result>
        </association>
    </resultMap>
  1. 嵌套查询(分步查询)
    <!--嵌套查询-->
    <resultMap id="empResultMapByUser3" type="com.cjw.mybatis.pojo.Book">
        <id property="bkId" column="bkId"></id>
        <result property="bkName" column="bkName"></result>
        <result property="bktype" column="bktype"></result>
        <result property="bkNum" column="bkNum"></result>
        <result property="bkCounty" column="bkCounty"></result>
        <result property="bkAuthor" column="bkAuthor"></result>
        <result property="bkCb" column="bkCb"></result>
        <result property="empName" column="emp_name"></result>
        <!--
               property 表示属性名
               select 表示设置分布查询的sql的唯一标识(namespace.SQLId
               或mapper接口的全类名.方法名)
               column 表示查询语句的条件
        -->
        <association property="user"
                     select="com.cjw.mybatis.dao.UserMapper.selectUserById"
                      column="userId">
        </association>
    </resultMap>

嵌套查询的优点: 可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息;
lazyLoadingEnabled: 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
aggressiveLazyLoading: 当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载。
此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和collection中的fetchType属性设置当前的分步查询是否使用延迟加载,fetchType="lazy(延迟加载) | eager(立即加载)"

  • 一对多查询
    一对多对应集合,多对一对应对象。
    collection:用来处理一对多的映射关系
    ofType:表示该属性对饮的集合中存储的数据的类型
    1. 嵌套结果
<resultMap id="DeptAndEmpResultMap" type="Dept">
	<id property="did" column="did"></id>
	<result property="deptName" column="dept_name"></result>
	<collection property="emps" ofType="Emp">
		<id property="eid" column="eid"></id>
		<result property="empName" column="emp_name"></result>
		<result property="age" column="age"></result>
		<result property="sex" column="sex"></result>
		<result property="email" column="email"></result>
	</collection>
</resultMap>
<!--Dept getDeptAndEmp(@Param("did") Integer did);-->
<select id="getDeptAndEmp" resultMap="DeptAndEmpResultMap">
	select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}
</select>
  1. 嵌套查询
/**
 * 通过分步查询,查询部门及对应的所有员工信息
 * 分步查询第一步:查询部门信息
 * @param did 
 * @return com.atguigu.mybatis.pojo.Dept
 * @date 2022/2/27 22:04
 */
Dept getDeptAndEmpByStepOne(@Param("did") Integer did);
<resultMap id="DeptAndEmpByStepOneResultMap" type="Dept">
	<id property="did" column="did"></id>
	<result property="deptName" column="dept_name"></result>
	<collection property="emps"
				select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
				column="did"></collection>
</resultMap>
<!--Dept getDeptAndEmpByStepOne(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepOne" resultMap="DeptAndEmpByStepOneResultMap">
	select * from t_dept where did = #{did}
</select>



/**
 * 通过分步查询,查询部门及对应的所有员工信息
 * 分步查询第二步:根据部门id查询部门中的所有员工
 * @param did
 * @return java.util.List<com.atguigu.mybatis.pojo.Emp>
 * @date 2022/2/27 22:10
 */
List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);/**
 * 通过分步查询,查询部门及对应的所有员工信息
 * 分步查询第二步:根据部门id查询部门中的所有员工
 * @param did
 * @return java.util.List<com.atguigu.mybatis.pojo.Emp>
 * @date 2022/2/27 22:10
 */
List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);
<!--List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepTwo" resultType="Emp">
	select * from t_emp where did = #{did}
</select>

九、动态SQL

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

9.1、if
  • if标签可通过test属性(即传递过来的数据)的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行
  • where后面添加一个恒成立条件1=1这个恒成立条件并不会影响查询的结果
  • 这个1=1可以用来拼接and语句,例如:当empName为null时
  • 如果不加上恒成立条件,则SQL语句为select * from t_emp where and age = ? and sex = ? and email = ?,此时where会与and连用,SQL语句会报错
  • 如果加上一个恒成立条件,则SQL语句为select * from t_emp where 1= 1 and age = ? and sex = ? and email = ?,此时不报错
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select * from t_emp where 1=1
	<if test="empName != null and empName !=''">
		and emp_name = #{empName}
	</if>
	<if test="age != null and age !=''">
		and age = #{age}
	</if>
	<if test="sex != null and sex !=''">
		and sex = #{sex}
	</if>
	<if test="email != null and email !=''">
		and email = #{email}
	</if>
</select>
9.2、where
  • where和if一般结合使用

    • where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字

    • where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and/or去掉

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

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

<!--这种用法是错误的,只能去掉条件前面的and/or,条件后面的不行-->
<if test="empName != null and empName !=''">
emp_name = #{empName} and
</if>
<if test="age != null and age !=''">
	age = #{age}
</if>
9.3、trim
  • trim用于去掉或添加标签中的内容
  • 常用属性
    • prefix:在trim标签中的内容的前面添加某些内容
    • suffix:在trim标签中的内容的后面添加某些内容
    • prefixOverrides:在trim标签中的内容的前面去掉某些内容
    • suffixOverrides:在trim标签中的内容的后面去掉某些内容
  • 若trim中的标签都不满足条件,则trim标签没有任何效果,也就是只剩下select * from t_emp
<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select * from t_emp
	<trim prefix="where" suffixOverrides="and|or">
		<if test="empName != null and empName !=''">
			emp_name = #{empName} and
		</if>
		<if test="age != null and age !=''">
			age = #{age} and
		</if>
		<if test="sex != null and sex !=''">
			sex = #{sex} or
		</if>
		<if test="email != null and email !=''">
			email = #{email}
		</if>
	</trim>
</select>
//测试类
@Test
public void getEmpByCondition() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
	List<Emp> emps= mapper.getEmpByCondition(new Emp(null, "张三", null, null, null, null));
	System.out.println(emps);
}

9.5、choose、when、otherwise

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

when至少要有一个,otherwise至多只有一个

<select id="getEmpByChoose" resultType="Emp">
	select * from t_emp
	<where>
		<choose>
			<when test="empName != null and empName != ''">
				emp_name = #{empName}
			</when>
			<when test="age != null and age != ''">
				age = #{age}
			</when>
			<when test="sex != null and sex != ''">
				sex = #{sex}
			</when>
			<when test="email != null and email != ''">
				email = #{email}
			</when>
			<otherwise>
				did = 1
			</otherwise>
		</choose>
	</where>
</select>
@Test
public void getEmpByChoose() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
	List<Emp> emps = mapper.getEmpByChoose(new Emp(null, "张三", 23, "男", "123@qq.com", null));
	System.out.println(emps);
}

相当于if a else if b else if c else d,只会执行其中一个

9.4、foreach
  • 属性

    • collection:设置要循环的数组或集合
    • item:表示集合或数组中的每一个数据
    • separator:设置循环体之间的分隔符,分隔符前后默认有一个空格,如,
    • open:设置foreach标签中的内容的开始符
    • close:设置foreach标签中的内容的结束符
  • 批量删除

<!--int deleteMoreByArray(Integer[] eids);-->
<delete id="deleteMoreByArray">
	delete from t_emp where eid in
	<foreach collection="eids" item="eid" separator="," open="(" close=")">
		#{eid}
	</foreach>
</delete>
@Test
public void deleteMoreByArray() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
	int result = mapper.deleteMoreByArray(new Integer[]{6, 7, 8, 9});
	System.out.println(result);
}
  • 批量添加
<!--int insertMoreByList(@Param("emps") List<Emp> emps);-->
<insert id="insertMoreByList">
	insert into t_emp values
	<foreach collection="emps" item="emp" separator=",">
		(null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
	</foreach>
</insert>
@Test
public void insertMoreByList() {
	SqlSession sqlSession = SqlSessionUtils.getSqlSession();
	DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
	Emp emp1 = new Emp(null,"a",1,"男","123@321.com",null);
	Emp emp2 = new Emp(null,"b",1,"男","123@321.com",null);
	Emp emp3 = new Emp(null,"c",1,"男","123@321.com",null);
	List<Emp> emps = Arrays.asList(emp1, emp2, emp3);
	int result = mapper.insertMoreByList(emps);
	System.out.println(result);
}
9.6、SQL片段
  • sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入

  • 声明sql片段:标签

<sql id="empColumns">eid,emp_name,age,sex,email</sql>
引用sql片段:<include>标签

<!--List<Emp> getEmpByCondition(Emp emp);-->
<select id="getEmpByCondition" resultType="Emp">
	select <include refid="empColumns"></include> from t_emp

十、MyBatis的缓存

缓存是只针对查询有效的

10.1、MyBatis的一级缓存
  • 一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就会从缓存中直接获取,不会从数据库重新访问
  • 使一级缓存失效的四种情况:
    • 不同的SqlSession对应不同的一级缓存
    • 同一个SqlSession但是查询条件不同(新的数据)
    • 同一个SqlSession两次查询期间执行了任何一次增删改操作(改变数据)
    • 同一个SqlSession两次查询期间手动清空了缓存
10.2、MyBatis的二级缓存
  • 二级缓存是SqlSessionFactory级别,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取

  • 二级缓存开启的条件

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

    • 在映射文件中设置标签
      在这里插入图片描述

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

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

org.apache.ibatis.cache.CacheException: Error serializing object.  Cause: 	java.io.NotSerializableException: com.cjw.mybatis.pojo.Book
  • 使二级缓存失效的情况:两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效
    /**
     * 一级缓存
     */
    @Test
    public void testUsetMapperMoreSelect () {
        //加载核心配置文件 获取sqlSession
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        //获取Mapper
        BookMapper mapper = sqlSession.getMapper(BookMapper.class);//代理模式
        List<Book> allBooks = mapper.getAllBookByUserAndSelect();
        sqlSession.clearCache();//清除缓存
        allBooks.forEach(System.out::println);
        List<Book> allBooks1 = mapper.getAllBookByUserAndSelect();
        allBooks1.forEach(System.out::println);
    }
10.3、二级缓存的相关配置
  • mapper配置文件中添加的cache标签可以设置一些属性
    • eviction属性:缓存回收策略
      • LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。
      • FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。
      • SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
      • WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
      • 默认的是 LRU
    • flushInterval属性:刷新间隔,单位毫秒
      • 默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句(增删改)时刷新
    • size属性:引用数目,正整数
      • 代表缓存最多可以存储多少个对象,太大容易导致内存溢出
    • readOnly属性:只读,true/false
      • true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。
      • false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false
    /**
     * 二级缓存
     */
    @Test
    public void testUsetMapperMoreSelectTwo () {
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            SqlSession sqlSessionOne = sqlSessionFactory.openSession(true);
            BookMapper mapper = sqlSessionOne.getMapper(BookMapper.class);
            List<Book> allBooks = mapper.getAllBookByUserAndSelect();
            allBooks.forEach(System.out::println);
            sqlSessionOne.close();
            SqlSession sqlSessionTwo = sqlSessionFactory.openSession(true);
            BookMapper mapperTwo = sqlSessionTwo.getMapper(BookMapper.class);
            List<Book> allBooksTwo = mapperTwo.getAllBookByUserAndSelect();
            allBooksTwo.forEach(System.out::println);
            sqlSessionTwo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
10.4、MyBatis缓存查询的顺序

先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用
如果二级缓存没有命中,再查询一级缓存
如果一级缓存也没有命中,则查询数据库
SqlSession关闭之后,一级缓存中的数据会写入二级缓存

10.5、整合第三方缓存EHCache

mybatis毕竟是一个持久层框架,可能不能是很专业,可以使用第三方缓存,但是只能代替二级缓存

  • 添加依赖
    <!-- Mybatis EHCache整合包 -->
    <dependency>
        <groupId>org.mybatis.caches</groupId>
        <artifactId>mybatis-ehcache</artifactId>
        <version>1.2.1</version>
    </dependency>
    <!-- slf4j日志门面的一个具体实现 -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>
  • 各个jar包的功能
jar包名称作用
mybatis-ehcacheMybatis和EHCache的整合包
ehcacheEHCache核心包
slf4j-apiSLF4J日志门面包
logback-classic支持SLF4J门面接口的一个具体实现
  • ehcache.xml
    名字必须叫ehcache.xml
<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!-- 磁盘保存路径 -->
    <diskStore path="D:\atguigu\ehcache"/>
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>
  • 设置二级缓存的类型
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  • 加入logback日志
    存在SLF4j时,作为简易日志的log4j将失效,此时我们需要借助SLF4j的具体实现logback来打印日志。创建logback的配置文件logback.xml``
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <!-- 指定日志输出的位置 -->
    <appender name="STDOUT"
              class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!-- 日志输出的格式 -->
            <!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -->
            <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
        </encoder>
    </appender>
    <!-- 设置全局日志级别。日志级别按顺序分别是:DEBUGINFOWARNERROR -->
    <!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
    <root level="DEBUG">
        <!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
        <appender-ref ref="STDOUT" />
    </root>
    <!-- 根据特殊需求指定局部日志级别 -->
    <logger name="com.atguigu.crowd.mapper" level="DEBUG"/>
</configuration>

EHCache配置文件说明

[16:32:50.933] [DEBUG] [main] [net.sf.ehcache.Cache] [Initialised cache: com.cjw.mybatis.dao.BookMapper]
[16:32:50.933] [DEBUG] [main] [net.sf.ehcache.config.ConfigurationHelper] [CacheDecoratorFactory not configured for defaultCache. Skipping for 'com.cjw.mybatis.dao.BookMapper'.]
[16:32:51.125] [DEBUG] [main] [com.cjw.mybatis.dao.BookMapper] [Cache Hit Ratio [com.cjw.mybatis.dao.BookMapper]: 0.0]
[16:32:51.131] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Opening JDBC Connection]
[16:32:51.357] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [Created connection 1412794598.]
[16:32:51.363] [DEBUG] [main] [com.cjw.mybatis.dao.BookMapper.getAllBookByUserAndSelect] [==>  Preparing: select * from book]
[16:32:51.387] [DEBUG] [main] [com.cjw.mybatis.dao.BookMapper.getAllBookByUserAndSelect] [==> Parameters: ]
[16:32:51.420] [DEBUG] [main] [com.cjw.mybatis.dao.UserMapper.selectUserById] [====>  Preparing: select * from user where userId = ?]
[16:32:51.420] [DEBUG] [main] [com.cjw.mybatis.dao.UserMapper.selectUserById] [====> Parameters: 1(String)]
[16:32:51.421] [DEBUG] [main] [com.cjw.mybatis.dao.UserMapper.selectUserById] [<====      Total: 1]
[16:32:51.423] [DEBUG] [main] [com.cjw.mybatis.dao.UserMapper.selectUserById] [====>  Preparing: select * from user where userId = ?]
[16:32:51.423] [DEBUG] [main] [com.cjw.mybatis.dao.UserMapper.selectUserById] [====> Parameters: 2(String)]
[16:32:51.424] [DEBUG] [main] [com.cjw.mybatis.dao.UserMapper.selectUserById] [<====      Total: 0]
[16:32:51.424] [DEBUG] [main] [com.cjw.mybatis.dao.UserMapper.selectUserById] [====>  Preparing: select * from user where userId = ?]
[16:32:51.424] [DEBUG] [main] [com.cjw.mybatis.dao.UserMapper.selectUserById] [====> Parameters: 4(String)]
[16:32:51.425] [DEBUG] [main] [com.cjw.mybatis.dao.UserMapper.selectUserById] [<====      Total: 1]
[16:32:51.425] [DEBUG] [main] [com.cjw.mybatis.dao.BookMapper.getAllBookByUserAndSelect] [<==      Total: 3]
Book{bkId=492035, bkName='三国衍射仪', bktype='未知', bkNum='null', bkCounty='null', bkAuthor='null', bkCb='null', userId='null', user=User{userId=1, userName='hh', userAge=456, userAddress='2222', userRole=1}, empName='qwe'}
Book{bkId=492036, bkName='三国衍射仪', bktype='未知', bkNum='null', bkCounty='null', bkAuthor='null', bkCb='null', userId='null', user=null, empName='qwww'}
Book{bkId=492037, bkName='三国衍射仪', bktype='未知', bkNum='null', bkCounty='null', bkAuthor='null', bkCb='null', userId='null', user=User{userId=4, userName='测试', userAge=12, userAddress='哈哈', userRole=null}, empName='www'}
[16:32:51.429] [DEBUG] [main] [net.sf.ehcache.store.disk.Segment] [put added 0 on heap]
[16:32:51.429] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@543588e6]]
[16:32:51.429] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [Returned connection 1412794598 to pool.]
[16:32:51.429] [DEBUG] [main] [com.cjw.mybatis.dao.BookMapper] [Cache Hit Ratio [com.cjw.mybatis.dao.BookMapper]: 0.5]
Book{bkId=492035, bkName='三国衍射仪', bktype='未知', bkNum='null', bkCounty='null', bkAuthor='null', bkCb='null', userId='null', user=User{userId=1, userName='hh', userAge=456, userAddress='2222', userRole=1}, empName='qwe'}
Book{bkId=492036, bkName='三国衍射仪', bktype='未知', bkNum='null', bkCounty='null', bkAuthor='null', bkCb='null', userId='null', user=null, empName='qwww'}
Book{bkId=492037, bkName='三国衍射仪', bktype='未知', bkNum='null', bkCounty='null', bkAuthor='null', bkCb='null', userId='null', user=User{userId=4, userName='测试', userAge=12, userAddress='哈哈', userRole=null}, empName='www'}

MyBatis的逆向工程

在这里插入图片描述

<dependencies>
	<!-- MyBatis核心依赖包 -->
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
		<version>3.5.9</version>
	</dependency>
	<!-- junit测试 -->
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.13.2</version>
		<scope>test</scope>
	</dependency>
	<!-- MySQL驱动 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>8.0.27</version>
	</dependency>
	<!-- log4j日志 -->
	<dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.17</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>8.0.27</version>
				</dependency>
			</dependencies>
		</plugin>
	</plugins>
</build>

QBC Query By Criteria,根据标准查询

即条件都是定义好的,只需要调用像对应的方法,就可以生成标准的条件
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值