Mybatis笔记

一、搭建框架

1、引入依赖

创建maven工程,设置打包方式为jar,配置pom.xml

<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> 
        <scope>test</scope> 
    </dependency> 
    <!-- MySQL驱动 --> 
    <dependency> 
        <groupId>mysql</groupId> 
        <artifactId>mysql-connector-java</artifactId> 
        <version>5.1.3</version> 
    </dependency> 
</dependencies>

2、创建核心配置文件

1、文件命名:mybatis-config.xml(建议)

2、主要作用:配置连接数据库的环境,配置Mybatis的全局配置信息

3、存放位置: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>
    
    <!--设置连接数据库的环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/MyBatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    
    <!--引入映射文件-->
    <mappers>
        <mapper resource="mappers/UserMapper.xml"/>
    </mappers>
</configuration>

3、创建mapper接口

1、MyBaits中的mapper接口相当于以前的dao

2、区别在于,mapper仅仅是接口,不需要提供实现类

public interface UserMapper {
    //添加用户信息
    int insertUser();
}

4、创建映射文件

相关概念:ORM(Object Relationship Mapping)对象关系映射

  • 对象:Java的实体类对象
  • 关系:关系型数据库
  • 映射:二者之间的对应关系
Java概念 数据库概念
属性 字段/列
对象 记录/行

1、映射文件的命名规则:实体类的类名+Mapper.xml

2、映射文件的主要作用:编写SQL,访问,操作表中数据

3、映射文件的存放位置:src/main/resources/mappers目录下

4、MyBatis中可以面向接口操作数据,前提是两个一致:

​ ❶ mapper接口的全类名映射文件的namespace 保持一致

​ ❷ mapper接口中方法名映射文件中SQL标签的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.atguigu.mybatis.mapper.UserMapper">
    
    <insert id="insertUser">
        insert into t_user values(null,'admin','123',23,'男','admin@qq.com')
    </insert>
    
    <select id="getUser" resultType="com.atguigu.mybatis.pojo.User">
        select * from t_user where id = 3
    </select>
</mapper>

查询功能的标签必须设置resultTyperesultMap

​ ▶ resultType:自动映射,用于属性名和表中字段名一致的情况

​ ▶ resultMap :自定义映射,用于一对多、多对一、属性名和表中字段名不一致的情况

5、功能测试

SqlSession:Java程序 和 数据库 之间的会话

@Test
public void mybatisTest() throws IOException {
    //加载核心配置文件
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    //获取SqlSessionFactoryBuilder
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    //获取SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    //获取SqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //获取mapper接口对象
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    //测试功能
    int result = mapper.insertUser();
    //提交事务
    sqlSession.commit();
}

6、开启日志

日志级别FATAL(致命)>ERROR(错误)>WARN(警告)>INFO(信息)>DEBUG(调试)

从左到右,打印的内容越来越详细

加入依赖

<!-- log4j日志 -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

配置文件

文件命名:log4j.xml

存放位置:src/main/resources目录下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug" />
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info" />
    </logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    </root>
</log4j:configuration>

二、核心配置文件

<?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?,settings?,typeAliases?,typeHandlers?,
        objectFactory?,objectWrapperFactory?,reflectorFactory?,
        plugins?,environments?,databaseIdProvider?,mappers? 
	-->

    <!-- 引入properties文件 -->
    <properties resource="jdbc.properties"/>

    <typeAliases>
        <!-- 
			typeAlias:设置某个具体的类型的别名
        	不设置alias属性,有默认别名,不区分大小写 
		-->
        <typeAlias type="com.atguigu.mybatis.pojo.User" alias="User"/>
        <!-- 以包为单位,设置该包下所有的类型都拥有默认别名 -->
        <package name="com.atguigu.mybatis.pojo"/>
    </typeAliases>

    <!-- 设置连接数据库的环境 -->
    <environments default="development">
        <environment id="development">
            <!--
                transactionManager:设置事务管理方法
                属性:
                type:设置事务的管理方法,type="JDBC|MANAGED"
                type="JDBC":设置当前环境的事务管理都必须手动处理
                type="MANAGED":设置事务被管理,例如spring中的AOP
            -->
            <transactionManager type="JDBC"/>
            <!--
                dataSource:设置数据源
                属性:
                type:设置数据源的类型,type="POOLED|UNPOOLED|JNDI"
                type="POOLED":使用数据库连接池
                type="UNPOOLED":不使用数据库连接池
                type="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>
    </environments>
    <!--引入映射文件-->
    <mappers>
<!--        <mapper resource="mappers/UserMapper.xml"/>-->
        <package name="com.atguigu.mybatis.mapper"/>
    </mappers>
</configuration>

三、获取参数值

MyBatis获取参数值的两种方式:${}#{}

${}:本质是字符串拼接,要注意单引号问题

#{}:本质是占位符赋值,会自动添加单引号

+++

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

使用${}和#{}以任意名称获取参数的值

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

MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1或param1,param2为键

因此,只需要通过${}和#{}访问map集合的键获取参数的值

3、map集合类型的参数

需要通过${}和#{}访问map集合的键获取参数的值

4、实体类类型的参数【推荐】

需要通过${}和#{}访问属性名获取参数的值

5、使用@Param标识参数【推荐】

使用@Param注解标识mapper接口中的方法参数

需要通过${}和#{}访问value属性值或param1获取参数的值

四、查询操作

1、若查询出的数据只有一条

​ ❶可以通过实体类对象接收

​ ❷可以通过List集合接收

​ ❸可以通过Map集合接收

2、若查询出的数据有多条

​ ❶可以通过实体类类型的List集合接收

​ ❷可以通过Map类型的List集合接收

​ ❸可以通过在mapper接口的方法上添加@MapKey注解

五、特殊SQL

1、模糊查询

Mapper接口中List<User> testMoHu(@Param("username") String username);

<select id="testMoHu" resultType="User">
    <!--select * from t_user where username like '%${username}%'-->
    <!--select * from t_user where username like concat('%', #{username} ,'%')-->
    select * from t_user where username like "%"#{username}"%"
</select>

2、批量删除

Mapper接口中int deleteMore(@Param("ids") String ids);

<delete id="deleteMore">
    delete from t_user where id in (${ids});
</delete>

3、动态设置表名

Mapper接口中List<User> getUserByTableName(@Param("tableName") String tableName);

<select id="getUserByTableName" resultType="User">
    select * from ${tableName}
</select>

4、获取自增的主键

Mapper接口中void insertUser(User user);

<!--    useGeneratedKeys=true:设置使用了自增的主键   -->
<!--    keyProperty=id:把主键存放在参数的id属性上    -->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
    insert into t_user values(null, #{username}, #{password}, #{age}, #{sex}, #{email});
</insert>

六、resultMap

1、字段和属性的映射处理

①使用别名

Mapper接口中List<Emp> getAllEmp();

<select id="getAllEmp" resultType="Emp">
    select eid, emp_name empName, age, sex, email from t_emp
</select>

②设置全局配置

核心配置文件添加如下配置:

<!-- 会自动将 _ 映射为 驼峰  user_name:userName -->
<settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

③使用resultMap

<resultMap id="empMap" type="Emp">
    <!-- id属性配置 主键字段 -->
    <!-- result属性配置 普通字段 -->
    <id property="eid" column="eid"/>
    <result property="empName" column="emp_name"/>
    <result property="age" column="age"/>
</resultMap>

<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultMap="empMap">
    select * from t_emp
</select>

2、多对一映射处理

Class Emp {
    private Integer eid;
    private String empName;
    private Dept dept;	//多对一
}
Class Dept {
    private Integer did;
    private String deptName;
}

+++

①级联方式

<resultMap id="empAndDeptResultMap" type="Emp">
    <id property="eid" column="eid"/>
    <result property="empName" column="emp_name"/>
    
    <result property="dept.did" column="did"/>
    <result property="dept.deptName" column="dept_name"/>
</resultMap>

<!--Emp getEmpAndDept(@Param("eid") Integer eid);-->
<select id="getEmpAndDept" resultMap="empAndDeptResultMap">
    select * from t_emp left join t_dept on t_emp.did = t_dept.did where eid = #{eid}
</select>

②使用association

<resultMap id="empAndDeptResultMapTwo" type="Emp">
    <id property="eid" column="eid"/>
    <result property="empName" column="emp_name"/>
    
    <association property="dept" javaType="Dept">
        <id property="did" column="did"/>
        <result property="deptName" column="dept_name"/>
    </association>
</resultMap>

<!--Emp getEmpAndDept(@Param("eid") Integer eid);-->
<select id="getEmpAndDept" resultMap="empAndDeptResultMapTwo">
    select * from t_emp left join t_dept on t_emp.did = t_dept.did where eid = #{eid}
</select>

③分步查询

1、分步查询的优点:可以实现延迟加载,需要在核心配置文件中进行配置

lazyLoadingEnabled:延迟加载的全局开关。开启时,所有关联对象都会延迟加载

2、resultMap标签 --> association标签 --> fetchType="lazy|eager"

​ 如上可以单独设置延迟加载,且优先级高于核心配置文件

​ ❶EmpMapper

<resultMap id="empAndDeptByStepResultMap" type="Emp">
    <id property="eid" column="eid"/>
    <result property="empName" column="emp_name"/>
    
    <association property="dept"
                 select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
                 column="did"
                 fetchType="lazy"/>
</resultMap>

<!--Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);-->
<select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
    select * from t_emp where eid = #{eid}
</select>

​ ❷DeptMapper

<!--Dept getEmpAndDeptByStepTwo(@Param("did") Integer did);-->
<select id="getEmpAndDeptByStepTwo" resultType="Dept">
    select * from t_dept where did = #{did}
</select>

3、一对多映射处理

class Dept {
    private Integer did;
    private String deptName;
    private List<Emp> emps;	//一对多
}
class Emp {
    private Integer eid;
    private String empName;
}

+++

①collection

<resultMap id="deptAndEmpResultMap" type="Dept">
    <id property="did" column="did"/>
    <result property="deptName" column="dept_name"/>
    
	<!-- ofType设置集合中实体类的类型 -->
    <collection property="emps" ofType="Emp">
        <id property="eid" column="eid"/>
        <result property="empName" column="emp_name"/>
    </collection>
</resultMap>

<!--Dept getDeptAndEmpById(@Param("did") Integer did);-->
<select id="getDeptAndEmpById" resultMap="deptAndEmpResultMap">
    select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}
</select>

②分步查询

​ ❶DeptMapper

<resultMap id="deptAndEmpResultMsp" type="Dept">
    <id property="did" column="did"/>
    <result property="deptName" column="dept_name"/>

    <collection property="emps"
                select="com.atguigu.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
                column="did"/>
</resultMap>

<!--Dept getDeptAndEmpByStepOne(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpResultMsp">
    select * from t_dept where did = #{did}
</select>

​ ❷EmpMapper

<!--List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepTwo" resultType="Emp">
    select * from t_emp where did = #{did}
</select>

七、动态SQL

动态SQL技术是一种根据特定条件动态拼接SQL语句的功能

1、if

if 标签可通过test属性的表达式进行判断

​ 结果为true,标签中的内容就会执行

​ 结果为false,标签中的内容就不会执行

<!--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}
</select>

2、where

1、where 和 if 一般结合使用:

​ ❶若标签中没有内容时,则where关键字不会添加

​ ❷若标签中有内容时,则自动添加where关键字,并将条件最前方多余的 and 或 or 去掉

2、where标签不能去掉条件后多余的 and 或 or

3、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>
    </where>
</select>

3、trim

1、标签中有内容时

​ ▶ prefix、suffix:添加内容到trim标签的前面或后面

​ ▶ prefixOverrides、suffixOverrides:在trim标签的内容前面或后面

2、标签中没有内容时

​ ▶ trim标签没有任何效果

<!--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>
    </trim>
</select>

4、choose

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

2、when 至少有一个,otherwise 至多有一个

<!--List<Emp> getEmpByChoose(Emp emp);-->
<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>
            <otherwise>
                did = 1
            </otherwise>
        </choose>
    </where>
</select>

5、foreach

属性:

​ ▶ collection:要循环的数组或集合

​ ▶ item:数组或集合中的每一个数据

​ ▶ separator:循环体之间的分隔符,左右自带空格

​ ▶ open:foreach标签中的开始符

​ ▶ close:foreach标签中的结束符

①批量删除,使用in

<!--int deleteMoreByArray(@Param("eids") Integer[] eids);-->
<delete id="deleteMoreByArray">
    delete from t_emp where eid in
    <foreach collection="eids" item="eid" separator="," open="(" close=")">
        #{eid}
    </foreach>
</delete>

②批量删除,使用or

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

③批量添加

<!--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>

6、SQL片段

设置SQL片段

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

应用SQL片段

<include refid="empColumns"/>

八、缓存

1、一级缓存

一级缓存是『 SqlSession级别 』的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据, 就会从缓存中直接获取,不会去重新查询数据库

一级缓存失效的四种情况:

​ ❶ 不同的SqlSession对应不同的一级缓存

​ ❷ 同一个SqlSession,但查询条件不同

​ ❸ 同一个SqlSession,两次查询期间进行了增删改操作

​ ❹ 同一个SqlSession,两次查询期间手动清空缓存

2、二级缓存

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

二级缓存开启条件:

​ ❶ 在核心配置文件中,设置全局变量属性cacheEnabled="true",默认为true

​ ❷ 在映射文件中设置标签 <cache />

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

​ ❹ 二级缓存必须在SqlSession关闭或提交之后,才会生效

二级缓存失效的情况:

​ ❶ 两次查询之间 进行增删改操作,会使一级和二级缓存同时失效

二级缓存相关配置:

​ ❶ eviction属性:缓存回收策略

​ ▶ LRU:最近最少使用,移除最长时间不被使用的对象【默认】

​ ▶ FIFO:先进先出,按对象进入缓存的顺序进行移除

​ ▶ SOFT:软引用,移除基于垃圾回收器状态和软引用规则的对象

​ ▶ WEAK:弱引用,更积极地移除基于垃圾收集器状态和弱引用规则的对象

​ ❷ flushInterval属性:刷新间隔,单位毫秒

​ ▶ 默认不进行设置,即进行增删改操作时进行刷新

​ ❸ size属性:引用数目,正整数

​ ▶ 缓存可以存储对象的最大值

​ ❹ readOnly属性:只读,true/false

​ ▶ true:只读缓存,会直接给调用者返回缓存对象中的实例对象。因此不可进行修改

​ ▶ false:读写缓存,会返回缓存对象的拷贝(通过序列化)。安全【默认】

3、缓存查询顺序

先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据

❷ 如果二级缓存没有命中,再查询一级缓存

❸ 如果一级缓存没有命中,则查询数据库

❹ SqlSession关闭后,一级缓存中的数据才会写入二级缓存

4、整合EHCache

①添加依赖

<!-- 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-ehcache Mybatis和EHCache的整合包
ehcache EHCache核心包
slf4j-api SLF4J日志门面包
logback-classic SLF4J接口的一个具体实现

③创建配置文件

文件命名: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日志

创建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>

    <!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR -->
    <!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
    <root level="DEBUG">
        <!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
        <appender-ref ref="STDOUT" />
    </root>

    <!-- 根据特殊需求指定局部日志级别 -->
    <logger name="com.atguigu.crowd.mapper" level="DEBUG"/>
</configuration>

九、逆向工程

1、配置步骤

①添加依赖和插件

<!-- 依赖MyBatis核心包 -->
<dependencies>
    <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>
        <scope>test</scope>
    </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>

<!-- 控制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>

②创建Mybatis的核心配置文件

文件命名:mybatis-config.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="jdbc.properties"/>

    <typeAliases>
        <package name=""/>
    </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>
        <package name=""/>
    </mappers>
</configuration>

③创建逆向工程的配置文件

文件名必须是: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="MyBatis3">
        
        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis"
                        userId="root"
                        password="root">
        </jdbcConnection>
        
        <!-- javaBean的生成策略-->
        <javaModelGenerator targetPackage="com.atguigu.mybatis.pojo" 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>

④执行MBG插件

双击插件 mybatis-generator:generate

2、QBC插件

@Test
public void testQBC() throws IOException {
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSession sqlSession = new SqlSessionFactoryBuilder().build(is).openSession(true);
    EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
    
    //查询所有数据
    List<Emp> list1 = mapper.selectByExample(null);
    list1.forEach(emp -> System.out.println(emp));
    
    //根据条件查询
    EmpExample example = new EmpExample();
    example.createCriteria().andEmpNameEqualTo("mary").andAgeGreaterThanOrEqualTo(10);
    example.or().andSexEqualTo("女");
    List<Emp> list2 = mapper.selectByExample(example);
    list2.forEach(emp -> System.out.println(emp));
    
    //普通修改 -- 当属性值为null时,会将相应的字段值设置为null
    mapper.updateByPrimaryKey(new Emp(12, "abc", 22, "男", null, 3));
    //条件修改 -- 当属性值为null时,不会设置到字段中
    mapper.updateByPrimaryKeySelective(new Emp(10, "abc", 22, "男", null, 3));
}

十、分页插件

1、配置步骤

添加依赖

<!-- 分页插件 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.2.0</version>
</dependency>

配置分页插件

<plugins>
    <!--设置分页插件-->
    <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>

2、使用

在查询功能之前实现分页功能

PageHelper.startPage(int pageNum, int pageSize);
//	pageNum:当前页的页码
//	pageSize:每页显示的条数

在查询功能之后实现分页功能

PageInfo<Emp> page = new PageInfo<>(list, 5);
//	list:分页的数据
//	 5  :表示当前导航分页的数量
posted @   微风赋值  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示