Mybatis学习笔记

Mybatis简介

1、Mybatis是什么?

        Mybatis是一个半自动的ORM持久层框架,支持自定义SQL、存储过程和高级映射。可以使用简单的xml或注解用于配置和原始映射,将接口和java的pojo(普通的java对象)映射成数据库中的记录

        什么是ORM?

        Object Relation Mapping,对象关系映射,对象指的是java对象,关系指的是数据库中的关系模型。所谓的对象关系映射指的是java对象和数据库的关系模型之间建立的一种对应关系。

2、Mybatis执行过程

(1)加载配置。配置来源于两个地方,一个是配置文件,一个是java代码上的注释。将SQL的配置信息加载成为一个个MappedStatement对象(包括传入参数映射配置、执行的SQL语句,结果映射配置),存储到内存中

(2)SQL解析。API接口层接收到调用请求时,会接收到传入SQL的ID和传入对象(Map、JavaBean或基本数据类型),Mybatis会根据SQL的ID找到对应的MappedStatement,然后根据传入的参数对象对MappedStatement进行解析,解析后获得最终要执行的SQL语句和参数。

(3)SQL执行。将最终得到的SQL和参数拿到数据库执行,得到操作数据的结果

(4)结果映射。将操作数据库的结果按照映射的配置进行转换,可以转换成HashMap、JavaBean或者基本数据类型,并将最终结果返回。

第一个Mybatis程序

1、创建maven项目

2、导入依赖

<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>
    
    <!--lombok-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
    </dependency>
</dependencies>

3、在resource下创建mybatis核心配置文件

(1)先在resource下创建文件jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/自己的数据库名称?userSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC
jdbc.username=数据库用户名
jdbc.password=数据库密码

(2)在resource下创建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文件-->
    <properties resource="jdbc.properties" />    
    <!--配置连接数据库的环境-->
    <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>
</configuration>

4、创建mapper接口

(1)创建数据库表user:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `email` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

(2)创建java实体类TUser(对应数据库表):

package com.cyj.mybatis.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class TUser {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String sex;
    private String email;
}

 (3) 创建mapper接口UserMapper:

package com.cyj.mybatis.mapper;
public interface UserMapper {
     int insertUser();
}

5、在resource下创建com/cyj/mybatis/mapper包,在该包下创建Mybatis映射文件UserMapper.xml

        要注意的点:

        1、映射文件的namespace的值要和mapper接口的全类名相同。

        2、映射文件的SQL语句的id要和mapper接口中的方法名一致。

<?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接口的全类名-->
<mapper namespace="com.cyj.mybatis.mapper.UserMapper">
    <insert id="insertUser">
        insert into user values(null, '王五', '123456', 25, '女', 'wangwu@163.com')
    </insert>
</mapper>

6、在核心配置文件mybatis-config.xml中引入映射文件

 <mappers>
        <!--以包为单位引入映射文件-->
        <package name="com.cyj.mybatis.mapper"/>
    </mappers>

       此时的项目结构截图

7、测试

@Test
public void testMybatis() throws IOException {
    //加载核心配置文件
    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    //获取SqlSessionFactoryBuilder
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    //获取SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    //获取SqlSession,并设置自动提交
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    //获取mapper接口对象
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    //测试功能
    int i = userMapper.insertUser();
    System.out.println("i:" + i);
}

Mybatis核心配置文件Mybatis-config.xml解析

        核心配置文件中的标签必须按照顺序写:

configuration
    properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
    environment(环境变量)
    transactionManager(事务管理器)
    dataSource(数据源)
    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" />
    
    <settings>
        <!--将表中字段的下划线自动转换为驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>
    
    <!--设置类型别名-->
    <typeAliases>
        <!--二选一,一般用第二个-->
        <!--设置单个的类型别名,别名不区分大小写-->
        <typeAlias type="com.cyj.mybatis.pojo.User" alias="User"></typeAlias>
        <!--设置包下的所有类型别名,默认为实体类名-->
        <package name="com.cyj.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>
        <!--二选一-->
        <!--1、单独引入映射文件-->
        <mapper resource="com\cyj\mybatis\mapper\UserMapper.xml"/>
        <!--
        2、以包为单位引入映射文件:
            (1)mapper接口所在的包要和映射文件所在的包一致
            (2)mapper接口要和映射文件的名字一致
        -->
        <package name="com.cyj.mybatis.mapper"/>
    </mappers>
</configuration>

SqlSession工具类,用来获取SqlSession

package com.cyj.mybatis.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtils {
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = null;
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSession;
    }
}

Mybatis的增删改查

        UserMapper接口

/**
 * 增加用户
 * @return
 */
int insertUser();

/**
 * 删除用户
 * @return
 */
int deleteUser();

/**
 * 修改用户
 * @return
 */
int updateUser();

/**
 * 查询单个用户
 * @return
 */
TUser selectUser();

/**
 * 查询所有用户
 * @return
 */
List<TUser> selectAllUser();

        映射文件

<!--int insertUser();-->
<insert id="insertUser">
    insert into user values(null, '田七', '123456', 28, '女', 'tianqi@163.com')
</insert>

<!--int deleteUser();-->
<delete id="deleteUser">
    delete from user where id = 6
</delete>

<!--int updateUser();-->
<update id="updateUser">
    update user set age = 50 where id = 5;
</update>

<!--TUser selectUserByUsername();-->
<select id="selectUser" resultType="com.cyj.mybatis.pojo.TUser">
    select * from user where username = "张三"
</select>

<!--List<TUser> selectAllUser();-->
<select id="selectAllUser" resultType="com.cyj.mybatis.pojo.TUser">
    select * from user;
</select>

        测试

@Test
public void InsertUserTest(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    int insertUser = userMapper.insertUser();
    System.out.println("insertUser:" + insertUser);
}

@Test
public void DeleteUserTest(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    int deleteUser = userMapper.deleteUser();
    System.out.println("insertUser:" + deleteUser);
}

@Test
public void UpdateUserTest(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    int updateUser = userMapper.updateUser();
    System.out.println("insertUser:" + updateUser);
}

@Test
public void SelectUserTest(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    TUser user = userMapper.selectUser();
    System.out.println("User:" + user);
}

@Test
public void SelectALlUserTest(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    List<TUser> userList = userMapper.selectAllUser();
    for (TUser user : userList) {
        System.out.println(user);
    }
}

查询功能需要在标签中设置resultType或者resultMap,用于设置实体类和数据库表的映射关系

        resultType:设置默认的映射关系,自动映射,用于属性名和表中字段名一致的情况

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

Mybatis获取参数值的两种方式

        ${}:本质是字符串拼接,使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号

        #{}:本质是占位符赋值,使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,不需要手动添加单引号

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

<!--User getUserByUsername(String username);-->
<!--#{}-->
<select id="getUserByUsername" resultType="com.cyj.mybatis.pojo.User">
    select * from user where username = #{username}
</select>

<!--${}-->
<select id="getUserByUsername" resultType="com.cyj.mybatis.pojo.User">
    select * from user where username = '#{username}'
</select>

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

Mybatis会将这些参数存放在map集合中,以两种方式进行存储

(1)以arg0、arg1......为键,参数为值

(2)以param1、param2......为键,以参数为值

<!--User CheckUserLogin(String username, String password);-->
<!--#{}-->
<select id="checkUserLogin" resultType="com.cyj.mybatis.pojo.User">
    select * from user where username = #{arg0} and password = #{arg1}
    或者
    select * form user where username = #{param1} and password = #{param2}
</select>

<!--${}-->
<select id="checkUserLogin" resultType="com.cyj.mybatis.pojo.User">
    select * from user where username = '${arg0}' and password = '${arg1}'
    或者
    select * form user where username = '${param1}' and password = '${param2}'
</select>

3、实体类类型的参数

<!--int insetUser(User user);-->
<!--#{}-->
<insert id="insetUser">
    insert into user values(null, #{username}, #{password}, #{age}, #{sex}, #{email})
</insert>

<!--${}-->
<insert id="insetUser">
    insert into user values(null, '${username}', '${password}', '${age}', '${sex}', '${email}')
</insert>

4、使用@Param标识参数

可以通过@Param注解标识mapper接口中的方法参数,此时,会将这些参数放在map集合中

(1)以@Param注解的value属性值为键,以参数为值;

(2)以param1,param2...为键,以参数为值;

 User checkLogin(@Param("username") String username, @Param("password") String password);

//Mybatis会将这些参数存放在map集合中,以两种方式进行存储
    (1)以命名的字符串为键,参数为值
    (2)以param1、param2......为键,以参数为值
<select id="checkLogin" resultType="com.cyj.mybatis.pojo.User">
    select * from user where username = #{username} and password = #{password}
    //或者
    select * from user where username = '${username}' and password = '${password}'
    //或者
    select * form user where username = #{param1} and password = #{param2}
    //或者
    select * form user where username = '${param1}' and password = '${param2}'
</select>

Mybatis特殊查询

1、模糊查询

List<User> getUserByUsername(@Param("username") String username);

select * from user where username like '%${username}%';
//或者
select * from user where username like concat('%', #{username}}, '%');
//或者
select * from user where username like "%"#{username}"%";

2、批量删除

        只能使用${}。如果使用#{},则解析后的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')

int deleteBatch(@Param("ids") String ids);

<delete id="deleteBatch">
delete from user where id in (${ids})
</delete>

3、字段名和属性名不一致的情况

创建emp和dept表

DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp`  (
  `eid` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `email` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `did` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`eid`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;


DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept`  (
  `did` int(11) NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`did`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

创建Emp对象和Dept对象

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Emp {
    private Integer eid;
    private String empName;
    private Integer age;
    private String sex;
    private String email;
    private Dept dept;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Dept {
    private Integer did;
    private String deptName;
}

1、为字段起别名,保持和属性名的一致

select eid, emp_name empName, age, sex, email from emp;

2、设置全局配置,在mybatis全局配置文件mybtis-config.xml中添加标签

//该标签要放在<properties>标签之下,<typeAliases>标签之上
<settings>
    <setting name = "mapUnderScoreToCamelCase", value = "true">
</settings>

3、通过resultMap设置自定义映射关系

<!--
    resultMap:设置自定义映射关系
        id:唯一标识
        type;查询的数据要映射的实体类类型
-->
<resultMap id = "empResultMap", type = "Emp">
    <id property = "id", column = "id">
    <result property = "empName", column = "emp_name">
    <result property = "age", column = "age">
</resultMap>

<!--List<Emp> getAllEmp();-->
<select id = "getAllEmp", resultmap = "empResultMap">
    select * from emp
</select>

自定义映射resultMap

1、处理多对一的映射关系

(1)级联属性赋值

<resultMap id = "empAndDeptResultMapOne", type = "Emp">
    <id property = "eid" column = "eid">
    <result property = "empName" column = "emp_name">
    <result property = "age" column = "age">
    <result property = "sex" column = "sex">
    <result property = "email" column = "email">
    <result property = "dept.did" column = "did">
    <result property = "dept.deptName" column = "dept_name">
</resultMap>

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

(2)使用association解决多对一的映射关系

<resultMap id = "empAndDeptResultMapTwo", type = "Emp">
    <id property = "eid" column = "eid">
    <result property = "empName" column = "emp_name">
    <result property = "age" column = "age">
    <result property = "sex" column = "sex">
    <result property = "email" column = "email">
    <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 emp left join dept on emp.did = dept.did where emp.eid = #{eid}>
</select>

               测试代码

@Test
public void MybatisTest01(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
    Emp emp = empMapper.getEmpAndDept(3);
    System.out.println("emp:" + emp);
}

2、处理一对多的映射关系

        设置Dept实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Dept {
    private Integer did;
    private String deptName;
    private List<Emp> emps;
}

        通过collection解决一对多的映射关系

                collection:用来处理一对多的映射关系

                ofType:表示该属性对饮的集合中存储的数据的类型

<resultMap id="getAllEmpResult" 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>

<!--List<Emp> getALlEmp(@Param("did") Integer did);-->
<select id="getALlEmp" resultMap="getAllEmpResult">
    select * from dept left join emp on dept.did = emp.did where dept.did = #{did}
</select>

        测试

@Test
public void MybatisTest02(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);
    List<Emp> empList = deptMapper.getALlEmp(1);
    System.out.println(empList);
}

动态sql

        什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句

if:

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

<!--List<Emp> grtEmpByCondition(Emp emp);-->
<select id="grtEmpByCondition" resultType="com.cyj.mybatis.pojo.Emp">
    select * from emp where 1 = 1
    <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>
</select>

 测试

@Test
public void dynamicTest(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    DynamicMapper dynamicMapper = sqlSession.getMapper(DynamicMapper.class);
    List<Emp> empList = dynamicMapper.grtEmpByCondition(new Emp(null, null, null, "男", null));
    for (Emp emp : empList) {
        System.out.println(emp);
    }
};

where

where和if一般结合使用:

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

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

<!--List<Emp> grtEmpByConditionTwo(Emp emp);-->
<select id="grtEmpByConditionTwo" resultType="com.cyj.mybatis.pojo.Emp">
    select * from 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>

        测试

@Test
public void dynamicTest(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    DynamicMapper dynamicMapper = sqlSession.getMapper(DynamicMapper.class);
    List<Emp> empList = dynamicMapper.grtEmpByCondition(new Emp(null, null, null, "男", null));
    for (Emp emp : empList) {
        System.out.println(emp);
    }
};

trim:用于去掉或添加标签中的内容

常用属性

        prefix:在trim标签中的内容的前面添加某些内容

        suffix:在trim标签中的内容的后面添加某些内容

        prefixOverrides:在trim标签中的内容的前面去掉某些内容

        suffixOverrides:在trim标签中的内容的后面去掉某些内容

<!--List<Emp> greEmpByConditionThree(Emp emp);-->
<select id="getEmpByConditionThree" resultType="com.cyj.mybatis.pojo.Emp">
    select * from emp
    <trim prefix="where" prefixOverrides="and|or">
        <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>
    </trim>
</select>

        测试

@Test
public void dynamicTest01(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    DynamicMapper dynamicMapper = sqlSession.getMapper(DynamicMapper.class);
    List<Emp> empList = dynamicMapper.getEmpByConditionThree(new Emp(null, null, null, "男", null));
    for (Emp emp : empList) {
        System.out.println(emp);
    }
}

choose、when、otherwise(相当于if...else if...else)when至少要有一个,otherwise至多只有一个

<!--List<Emp> getEmpByOtherwise(Emp emp);-->
<select id="getEmpByOtherwise" resultType="com.cyj.mybatis.pojo.Emp">
    select * from 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 dynamicTest02(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    DynamicMapper dynamicMapper = sqlSession.getMapper(DynamicMapper.class);
    List<Emp> empList = dynamicMapper.getEmpByOtherwise(new Emp(null, null, null, "男", null));
    for (Emp emp : empList) {
        System.out.println(emp);
    }
}

foreach

属性:

        collection:设置要循环的数组或集合

        item:表示集合或数组中的每一个数据

        separator:设置循环体之间的分隔符,分隔符前后默认有一个空格,如,

        open:设置foreach标签中的内容的开始符

        close:设置foreach标签中的内容的结束符

        批量删除

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

        测试

@Test
public void deleteTest(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    DynamicMapper dynamicMapper = sqlSession.getMapper(DynamicMapper.class);
    int deleteNum = dynamicMapper.deleteEmpByIdArray(new Integer[]{5, 6, 7});
    System.out.println(deleteNum);
}

         批量增加

<!--int insertEmpByList(@Param("empList") List<Emp> empList);-->
<insert id="insertEmpByList">
    insert into emp values
    <foreach collection="empList" item="emp" separator=",">
        (null, #{emp.empName}, #{emp.age}, #{emp.sex}, #{emp.email}, null)
    </foreach>
</insert>

        测试

@Test
public void insertTest(){
    SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    DynamicMapper dynamicMapper = sqlSession.getMapper(DynamicMapper.class);
    Emp emp1 = new Emp(null, "猪八戒", 24, "男", "123456@163.com");
    Emp emp2 = new Emp(null, "孙悟空", 25, "男", "123456@163.com");
    Emp emp3 = new Emp(null, "沙和尚", 30, "男", "123456@163.com");
    Emp emp4 = new Emp(null, "唐三藏", 35, "男", "123456@163.com");
    List<Emp> empList = Arrays.asList(emp1, emp2, emp3, emp4);
    int insertNum = dynamicMapper.insertEmpByList(empList);
    System.out.println(insertNum);
}

sql片段

<sql id="allColumn">eid, emp_name empName, age, sex, email</sql>
<!--List<Emp> getAllEmp();-->
<select id="getAllEmp" resultType="com.cyj.mybatis.pojo.Emp">
    select <include refid="allColumn"></include> from emp
</select>

Mybatis缓存

1、什么是缓存

(1)缓存就是内存中的临时数据。将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(数据库)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题

(2) 为什么使用缓存?

减少和数据库的交互次数,减少系统开销,提高系统效率

(3) 什么样的数据可以使用缓存?

经常查询并且不经常改变的数据

2、Mybatis一级缓存

        一级缓存是SqlSession级别的,通过同一个SqlSession查询到的数据会被缓存,下次查询相同的数据时会直接从缓存中获得,不会再去查询数据库。

一级缓存会失效的情况:

(1)不同的SqlSession对应不同的一级缓存

(2)同一个SqlSession但是查询条件不相同

(3)同一个SqlSession两次查询中间进行过增删改操作

(4)同一个SqlSession两次查询中间手动清空了缓存

3、Mybatis二级缓存

        二级缓存是SqlSessionFactory级别的,通过同一个SqlSessionFactory创建的SqlSession查询的结果会被缓存

二级缓存开启条件

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

<settings>
    <!--显示的开启全局缓存-->
    <setting name="cacheEnabled" value="true"/>
    <!--下划线转驼峰-->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

(2)在映射文件中设置标签

<!--mapper接口的全类名-->
<mapper namespace="com.cyj.mybatis.mapper.CacheMapper">
    <!--在当前CacheMapper.xml中使用二级缓存-->
    <cache
        eviction="FIFO"
        flushInterval="60000"
        size="512"
        readOnly="true"/>
    <!--Emp getEmpByEid(@Param("eid") Integer eid);-->
    <select id="getEmpByEid" resultType="com.cyj.mybatis.pojo.Emp">
        select * from emp where eid = #{eid}
    </select>
</mapper>

(3)二级缓存必须在SqlSession关闭或者提交后才能生效

(4)查询的数据所对应的实体类必须实现序列化接口

二级缓存失效的情况:两次查询期间进行了任意的增删改操作

二级缓存的相关配置:

(1)eviction属性:缓存回收策略

        LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。(默认)

        FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。

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

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

(2)flushInterval属性:刷新间隔,单位毫秒

        默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句(增删改)时刷新

(3)size属性:引用数目,正整数

        代表缓存最多可以存储多少个对象,太大容易导致内存溢出

(4)readOnly属性:只读,true/false

        true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。

        false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是false

4、Mybatis缓存查询的顺序

(1)先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用

(2)如果二级缓存没有命中,再查询一级缓存

(3)如果一级缓存也没有命中,则查询数据库

(4)SqlSession关闭之后,一级缓存中的数据会写入二级缓存

5、第三方缓存EHCache

(1)添加依赖

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

(2)创建EHCache的配置文件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:\mybatis\ehcache"/>
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="true"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

<!-- 
属性说明:
diskStore:指定数据在磁盘中的存储位置。
defaultCache:当借助 CacheManager.add("demoCache") 创建 Cache 时,EhCache 便会采用 <defalutCache/> 指定的的管理策略。
 
必须的属性:
maxElementsInMemory - 在内存中缓存的 element 的最大数目。
maxElementsOnDisk - 在磁盘上缓存的 element 的最大数目,若是 0 表示无穷大。
eternal - 设定缓存的 elements 是否永远不过期。如果为 true,则缓存的数据始终有效,如果为 false 那么还要根据 timeToIdleSeconds,timeToLiveSeconds 判断。
overflowToDisk - 设定当内存缓存溢出的时候是否将过期的 element 缓存到磁盘上。
 
可选的属性:
timeToIdleSeconds - 当缓存在 EhCache 中的数据前后两次访问的时间超过 timeToIdleSeconds 的属性取值时,这些数据便会删除,默认值是 0,也就是可闲置时间无穷大。
timeToLiveSeconds - 缓存 element 的有效生命期,默认是 0,也就是 element 存活时间无穷大。
diskSpoolBufferSizeMB - 这个参数设置 DiskStore (磁盘缓存)的缓存区大小.默认是 30MB.每个 Cache 都应该有自己的一个缓冲区。
diskPersistent - 在 VM 重启的时候是否启用磁盘保存 EhCache 中的数据,默认是 false。
diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是 120 秒。每个 120s,相应的线程会进行一次 EhCache 中数据的清理工作。
memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的 element 加入的时候, 移除缓存中 element 的策略。默认是 LRU(最近最少使用),可选的有 LFU(最不常使用)和 FIFO(先进先出)。
 -->

(3)设置二级缓存的类型

        在映射文件CacheMapper.xml中设置缓存的类型

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

(4)创建logback日志文件ogback.xml,加入logback日志

<?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.cyj.mybatis.mapper" level="DEBUG"/>
</configuration>

Mybatis逆向工程

1、在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>

    <!--lombok-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</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>

2、创建mybatis核心配置文件

<?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 core file-->
<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>

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

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

4、测试

@Test
    public void GeneratorTest(){
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

            //查询所有数据
//            List<Emp> empList = empMapper.selectByExample(null);
//            for (Emp emp : empList) {
//                System.out.println(emp);
//            }

            //根据条件查询
//            EmpExample empExample = new EmpExample();
//            empExample.createCriteria().andEmpNameEqualTo("张三");
//            List<Emp> empList = empMapper.selectByExample(empExample);
//            for (Emp emp : empList) {
//                System.out.println(emp);
//            }

            //updateByPrimaryKey:通过主键进行数据修改,如果某一个值为null,也会将对应的字段改为null
            empMapper.updateByPrimaryKey(new Emp(1, "admin", 22, "女", "123@163.com", 2));
            //updateByPrimaryKeySelective():通过主键进行选择性数据修改,如果某个值为null,则不修改这个字段
            empMapper.updateByPrimaryKeySelective(new Emp(1, "admin", 22, null, "123@163.com", 2));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

分页插件

1、添加依赖

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<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>

3、在查询功能之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能

@Test
public void pageHelperTest(){
    try {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

        //查询第一页,每页三条数据
        PageHelper.startPage(1, 3);
        List<Emp> empList = empMapper.selectByExample(null);
        for (Emp emp : empList) {
            System.out.println(emp);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迟小歪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值