首页 > 其他分享 >Mybatis入门

Mybatis入门

时间:2022-10-31 18:33:11浏览次数:49  
标签:缓存 入门 映射 标签 查询 MyBatis emp Mybatis

一、MyBatis历史及特性

  • MyBatis最初是Apache的一个开源项目iBatis, 2010年6月这个项目由Apache Software Foundation迁移到了Google Code。
    随着开发团队转投Google Code旗下,iBatis3.x正式更名为MyBatis。代码于2013年11月迁移到Github。
  • MyBatis特性
  1. MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架
  2. MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集
  3. MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录
  4. MyBatis 是一个 半自动的ORM(Object Relation Mapping)框架

二、MyBatis使用

  • 引入依赖
 <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>
  • 创建MyBatis核心配置文件

习惯上命名为mybatis-config.xml,这个文件名仅仅只是建议,并非强制要求。
核心配置文件主要用于配置连接数据库的环境以及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>  
	<!--设置连接数据库的环境-->  
	<environments default="development">  
		<environment id="development">  
			<transactionManager type="JDBC"/>  
			<dataSource type="POOLED">  
				<property name="driver" value="com.mysql.cj.jdbc.Driver"/>  
				<property name="url" value="jdbc:mysql://localhost:3306/MyBatis"/>  
				<property name="username" value="root"/>  
				<property name="password" value="123456"/>  
			</dataSource>  
		</environment>  
	</environments>  
	<!--引入映射文件-->  
	<mappers>  
		<mapper resource="mappers/UserMapper.xml"/>  
	</mappers>  
</configuration>
  • 创建实体类及Mapper接口
public class User {
    private Integer id;

    private String userName;

    private String passWord;

    private Integer age;

    private String gender;

    private String email;

    public User() {

    }
    //省略get/set方法
}
public interface UserMapper {  
	/**  
	* 添加用户信息  
	*/  
	int insertUser();  
}
  • 创建MyBatis映射文件

MyBatis映射文件用于编写SQL,访问以及操作表中的数据;一个映射文件对应一个实体类,对应一张表的操作
mapper接口的全类名和映射文件的命名空间(namespace)保持一致,mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致
映射文件的命名规则是表所对应的实体类的类名+Mapper.xml 如UserMapper.xml

<?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">  
	<!--int insertUser();-->  
	<insert id="insertUser">  
		insert into t_user values(null,'张三','123',23,'女')  
	</insert>  
</mapper>

二、核心配置文件详解

核心配置文件中的标签必须按照固定的顺序(有的标签可以不写,但顺序一定不能乱):
properties、settings、typeAliases、typeHandlers、objectFactory、objectWrapperFactory、
reflectorFactory、plugins、environments、databaseIdProvider、mappers

<?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文件,此时就可以${属性名}的方式访问属性值-->
    <properties resource="jdbc.properties"></properties>
    <settings>
        <!--将表中字段的下划线自动转换为驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>
    <typeAliases>
        <!--
        typeAlias:设置某个具体的类型的别名
        属性:
        type:需要设置别名的类型的全类名
        alias:设置此类型的别名,且别名不区分大小写。若不设置此属性,该类型拥有默认的别名,即类名
        -->
        <!--<typeAlias type="com.atguigu.mybatis.bean.User"></typeAlias>-->
        <!--<typeAlias type="com.atguigu.mybatis.bean.User" alias="user">
        </typeAlias>-->
        <!--以包为单位,设置改包下所有的类型都拥有默认的别名,即类名且不区分大小写-->
        <package name="com.atguigu.mybatis.bean"/>
    </typeAliases>
    <!--
    environments:设置多个连接数据库的环境
    属性:
	    default:设置默认使用的环境的id
    -->
    <environments default="mysql_test">
        <!--
        environment:设置具体的连接数据库的环境信息
        属性:
	        id:设置环境的唯一标识,可通过environments标签中的default设置某一个环境的id,表示默认使用的环境
        -->
        <environment id="mysql_test">
            <!--
            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="UserMapper.xml"/> -->
        <!--
        以包为单位,将包下所有的映射文件引入核心配置文件
        注意:
			1. 此方式必须保证mapper接口和mapper映射文件必须在相同的包下
			2. mapper接口要和mapper映射文件的名字一致
        -->
        <package name="com.atguigu.mybatis.mapper"/>
    </mappers>
</configuration>

三、查询及特殊SQL

四、自定义映射ResultMap

1) ResultMap用来处理字段和属性的映射关系

  • resultMap属性:
    • id:表示自定义映射的唯一标识,不能重复
    • type:查询的数据要映射的实体类的类型
    • 子标签:
    • id:设置主键的映射关系
    • result:设置普通字段的映射关系
      • 子标签属性:
      • property:设置映射关系中实体类中的属性名
      • column:设置映射关系中表中的字段名
    <!-- 1.resultMap可以用来处理字段名和属性名不一致问题 -->
    <resultMap id="empResultMap" type="employee">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
    </resultMap>

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

2) ResultMap处理多对一关系

使用 association 标签处理映射关系。

  • association:处理多对一的映射关系
    • property:需要处理多对的映射关系的属性名
    • javaType:该属性的类型
<resultMap id="empAndDeptByIdResultMap" type="employee">
    <id column="emp_id" property="empId"></id>
    <result column="emp_name" property="empName"></result>
    <result column="age" property="age"></result>
    <result column="gender" property="gender"></result>
    <association property="dept" javaType="department">
        <id column="dept_id" property="deptId"></id>
        <result column="dept_name" property="deptName"></result>
    </association>
</resultMap>

<!-- Employee getEmpAndDeptById(@Param("empId")Integer empId); -->
<select id="getEmpAndDeptById" resultMap="empAndDeptByIdResultMap">
    SELECT t_emp.*,t_dept.dept_name
    FROM t_emp LEFT JOIN t_dept
    ON t_emp.dept_id = t_dept.dept_id
    WHERE t_emp.emp_id = #{empId}
</select>

3) ResultMap处理一对多关系
使用 collection 标签处理映射关系。

  • collection:用来处理一对多的映射关系
    • ofType:表示该属性对饮的集合中存储的数据的类型
<resultMap id="deptAndEmpByIdResultMap" type="department">
    <id column="dept_id" property="deptId"></id>
    <result column="dept_name" property="deptName"></result>
    <collection property="emps" ofType="employee">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
    </collection>
</resultMap>

<!-- Department getDeptAndEmpById(@Param("deptId")Integer deptId); -->
<select id="getDeptAndEmpById" resultMap="deptAndEmpByIdResultMap">
    SELECT * FROM t_dept LEFT JOIN t_emp
        ON t_dept.dept_id = t_emp.dept_id
    where t_dept.dept_id = #{deptId}
</select>

4)分步查询及延迟加载

  • 分步查询、
    属性:
    • select:设置分布查询的sql的唯一标识(namespace.SQLId或mapper接口的全类名.方法名)
    • column:设置分步查询的条件
<resultMap id="empAndDeptByStepResultMap" 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>
	<association property="dept"
		select="com.atguigu.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
		column="did">
	</association>
</resultMap>

<!--Emp getEmpAndDeptByStepOne(@Param("eid") Integer eid);-->
<select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
	select * from t_emp where eid = #{eid}
</select>
  • 分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息:
  • lazyLoadingEnabled:默认值false延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
    • aggressiveLazyLoading:默认值true,当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个属性会按需加载
  • 此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和collection中的fetchType属性设置当前的分步查询是否使用延迟加载,fetchType="lazy(延迟加载)|eager(立即加载)"
<settings>
	<!--开启延迟加载-->
	<setting name="lazyLoadingEnabled" value="true"/>
</settings>

五、动态SQL

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能。

1) if标签

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

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>

3)trim标签

trim标签用于去掉或者添加标签中内容。
常用属性:

  • prefix:在trim标签中的内容的前面添加某些内容
  • suffix:在trim标签中的内容的后面添加某些内容
  • prefixOverrides:在trim标签中的内容的前面去掉某些内容
  • suffixOverrides:在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>
		<if test="sex != null and sex !=''">
			sex = #{sex} or
		</if>
		<if test="email != null and email !=''">
			email = #{email}
		</if>
	</trim>
</select>

4)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>

5)foreach

常用属性:

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

foreach实现批量增加和删除

  • 批量增加
<!--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>
  • 批量删除
<!--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>

6)SQL片段

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

  • 声明sql片段:<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
</select>

六、MyBatis缓存

1)mybatis一级缓存

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

  • 一级缓存失效的四种情况
1. 不同的SqlSession对应不同的一级缓存
2. 同一个SqlSession但是查询条件不同
3. 同一个SqlSession两次查询期间执行了任何一次增删改操作
4. 同一个SqlSession两次查询期间手动清空了缓存

2)mybatis二级缓存

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

  • 二级缓存开启条件
1. 在核心配置文件中,设置全局配置属性cacheEnabled="true",默认为true,不需要设置
2. 在映射文件中设置标签<cache />
3. 二级缓存必须在SqlSession关闭或提交之后有效
4. 查询的数据所转换的实体类类型必须实现序列化的接口
  • 二级缓存只有当两次查询之前执行了增删改,就会使一级和二级缓存同时失效

3)二级缓存相关配置

  • 在mapper配置文件中添加的cache标签可以设置一些属性
  • eviction属性:缓存回收策略
  • LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。
    • FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。
    • SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
    • WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
    • 默认的是 LRU
  • flushInterval属性:刷新间隔,单位毫秒
  • 默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句(增删改)时刷新
  • size属性:引用数目,正整数
  • 代表缓存最多可以存储多少个对象,太大容易导致内存溢出
  • readOnly属性:只读,true/false
  • true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。
    • false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false

4)缓存查询顺序

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

七、MyBatis逆向工程

正向工程:先创建Java实体类,由框架负责根据实体类生成数据库表。Hibernate是支持正向工程的
逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:

  • Java实体类
  • Mapper接口
  • Mapper映射文件

1)创建逆向工程步骤

  • 添加依赖和插件
    <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>
  • 创建逆向工程配置文件
    • 文件名称必须是: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">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- 数据库的连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/ssm"
                        userId="root"
                        password="123456">
            <!--解决mysql8.0以后重复生成所有表的问题-->
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>
        <!-- javaBean的生成策略-->
        <javaModelGenerator targetPackage="com.snow.mybatis.pojo" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- SQL映射文件的生成策略 -->
        <sqlMapGenerator targetPackage="com.snow.mybatis.mapper"
                         targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- Mapper接口的生成策略 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.snow.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>
  • 执行Maven插件
    image

2)QBC

查询
  • selectByExample:按条件查询,需要传入一个example对象或者null;如果传入null,则表示没有条件,也就是查询所有数据
  • example.createCriteria().andxxx:创建条件对象,通过andXXX方法为SQL添加查询添加,每个条件之间是and关系
  • example.or().xxx:将之前添加的条件通过or拼接其他条件
	SqlSession sqlSession = SqlSessionUtil.getSqlSession();
	EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
	//根据id查询用户
	Emp emp = mapper.selectByPrimaryKey(1);
	System.out.println(emp);

	//查询所有数据
	List<Emp> emps = mapper.selectByExample(null);
	emps.forEach(System.out::println);

	//根据条件查询用户
	EmpExample example = new EmpExample();
	//设置条件
	example.createCriteria().andEmpNameEqualTo("lisi").andGenderEqualTo("男");
	example.or().andAgeGreaterThan(20);
	List<Emp> emps = mapper.selectByExample(example);
	emps.forEach(System.out::println);
增删改
  • updateByPrimaryKey:通过主键进行数据增删改,如果某一个值为null,也会将对应的字段改为null
  • updateByPrimaryKeySelective():通过主键进行选择性数据修改,如果某个值为null,则不修改这个字段
        //测试新增功能
        Emp emp = new Emp(null,"小千",19,"女",null);
        mapper.insertSelective(emp);

        //测试修改功能
        EmpExample example = new EmpExample();
        Emp emp = new Emp(2,"小张",null,null,null);
        mapper.updateByPrimaryKeySelective(emp);

        //测试删除功能
        mapper.deleteByPrimaryKey(5);

八、MyBatis使用分页插件

分页插件配置与使用

  • 1.添加依赖
<dependency>
	<groupId>com.github.pagehelper</groupId>
	<artifactId>pagehelper</artifactId>
	<version>5.2.0</version>
</dependency>
  • 2.配置分页插件
    在MyBatis的核心配置文件(mybatis-config.xml)中配置插件
<plugins>
	<!--设置分页插件-->
	<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>

image

  • 3.开启分页功能
    在查询功能之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能
    @Test
    public void testPageHelper(){
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        //开启分页功能
        PageHelper.startPage(1,4);
        List<Emp> emps = mapper.selectByExample(null);
        emps.forEach(System.out::println);
        PageInfo<Emp> pageInfo = new PageInfo<>(emps,5);
        System.out.println(pageInfo);
    }
获取分页数据

在查询获取list集合之后,使用PageInfo<T> pageInfo = new PageInfo<>(List<T> list, intnavigatePages)获取分页相关数据

  • list:分页之后的数据
  • navigatePages:导航分页的页码数
PageInfo{pageNum=1, pageSize=4, size=4, startRow=1, endRow=4, total=16, pages=4, 
list=Page{count=true, pageNum=1, pageSize=4, startRow=0, endRow=4, total=16, pages=4, reasonable=false, pageSizeZero=false}
[Emp{empId=1, empName='snow', age=20, gender='男', deptId=1}, Emp{empId=2, empName='小张', age=18, gender='男', deptId=1}, Emp{empId=3, empName='lisi', age=30, gender='男', deptId=3}, Emp{empId=4, empName='junjun', age=20, gender='女', deptId=2}], 
prePage=0, nextPage=2, isFirstPage=true, isLastPage=false, hasPreviousPage=false, hasNextPage=true, 
navigatePages=5, navigateFirstPage=1, navigateLastPage=4, navigatepageNums=[1, 2, 3, 4]}

其中list中的数据等同于方法一中直接输出的page数据

  • pageNum:当前页的页码
  • pageSize:每页显示的条数
  • size:当前页显示的真实条数
  • total:总记录数
  • pages:总页数
  • prePage:上一页的页码
  • nextPage:下一页的页码
  • isFirstPage/isLastPage:是否为第一页/最后一页
  • hasPreviousPage/hasNextPage:是否存在上一页/下一页
  • navigatePages:导航分页的页码数
  • navigatepageNums:导航分页的页码,[1,2,3,4,5]

标签:缓存,入门,映射,标签,查询,MyBatis,emp,Mybatis
From: https://www.cnblogs.com/Snowclod/p/16829181.html

相关文章

  • [Telink][TLSR8251] [泰凌微]入门上手教程(IDE+SDK+烧录)
    相关下载​​IDE下载​​​​SDKV3.4.2.1_Patch_0001​​​​烧录工具下载​​一、IDE的使用必须以管理员身份运行必须安装到C:安装完毕后,开始下面的导入SDK。解压压缩包......
  • Mybatis查看最终执行的SQL
    SimpleExecutor-->doQuery  ......
  • Solr 8.11入门教程(4)中文分词
    中文分词默认对中文分词的效果并不好,我们添加IK分词。下载重新下载:先下载solr8版本对应的ik分词器,分词器GitHub源码地址:https://github.com/magese/ik-analyzer-solr添......
  • gstreamer入门
    Basicsgstreamerconsistsofgst-launch-1.0andgst-inspect-1.0gst-launch-1.0launchesanewstreampipelinewiththepropertiesyouset.gst-inspect-1.0prov......
  • MATLAB入门实验-MATLAB实验1...MATLAB实验8
    MATLAB入门实验-MATLAB实验1...MATLAB实验8实验1MATLAB系统环境运算基础一、实验目的掌握启动和退出MATLAB的方法。掌握MATLAB操作界面的组成。掌握建立矩阵的方法......
  • Solr 8.11入门教程(2)创建core
    新建core添加core命令添加使用命令比较简单~$bin/solrcreate-cmytest[core名称]这样就添加完了。CoreAdmin就可以看到了。手动添加手动添加相对复杂一些,需要提......
  • Solr 8.11入门教程(2)创建core
    新建core添加core命令添加使用命令比较简单~$bin/solrcreate-cmytest[core名称]这样就添加完了。CoreAdmin就可以看到了。手动添加手动添加相对复杂一些,需要提前创建目......
  • Hibernate的入门(概念1):
    什么是持久化类? 持久化类的编写规则? 区分自然主键和代理主键? 主键生成策略?  ......
  • Hibernate的入门(增删改查):
    注意:本次的记录是在上一篇Hibernate入门的基础上应用的1.目录2.实体类修改1packagecom.itheima.domain;23/*4*客户的javaBean5*@authorchenyanlong6*/......
  • Solr 8.11入门教程(2)新建core
    Solr8.11入门教程(2)新建core添加core命令添加使用命令比较简单~$bin/solrcreate-cmytest[core名称]这样就添加完了。CoreAdmin就可以看到了。手动添加手动......