MyBatis相关整理(二)

一、单元测试模块

添加单元测试依赖

junit
junit
4.12

创建单元测试类:在被测试类名后alt+insert — 选择Test 或在类名后单击右键进行操作
在这里插入图片描述
测试代码

package com.qfedu.dao;

import com.qfedu.pojo.Student;
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;

import static org.junit.Assert.*;

public class StudentDAOTest {

    @org.junit.Test
    public void insertStudent() {

        try {
            //加载mybatis配置文件
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //会话工厂
            SqlSessionFactory factory = builder.build(is);
            //会话(连接)
            SqlSession sqlSession = factory.openSession();
            //通过会话获取DAO对象
            StudentDAO studentDAO = sqlSession.getMapper(StudentDAO.class);
            //测试StudentDAO中的方法
            int i = studentDAO.insertStudent(new Student(0, "10001", "张三", "男", 21));
            //需要手动提交
            sqlSession.commit();
            System.out.println(i);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @org.junit.Test
    public void deleteStudent() {
    }
}

二、MyBatis主配置文件

mybatis-config.xml 是MyBatis框架的主配置文件,只要用于配置MyBatis数据源及属性信息

  • properties标签:用于设置键值对,或者加载属性文件
    在resources目录下创建jdbc.properties文件,配置键值对如下:
mysql_driver=com.mysql.jdbc.Driver
mysql_url=jdbc:mysql://localhost:3306/db_2010_fmwy?characterEncoding=utf-8
mysql_username=root
mysql_password=admin123

在mybatis-config.xml中通过properties标签引用jdbc.properties文件;引入之后,在配置environment时可以直接使用jdbc.properties的key获取对应的value
在这里插入图片描述

  • settings标签:设置mybatis的属性
<!--设置mybatis的属性-->
<settings>
    <!-- 启动二级缓存-->
    <setting name="cacheEnabled" value="true"/>
    <!-- 启动延迟加载 -->
    <setting name="lazyLoadingEnabled" value="true"/>
</settings>
  • typeAliases标签:给实体类取别名
<!--typeAliases标签用于给实体类取别名,在映射文件中可以直接使用别名来替代实体类的全限定名-->
<typeAliases>
    <typeAlias type="com.qfedu.pojo.Student" alias="Student"></typeAlias>
    <typeAlias type="com.qfedu.pojo.Book" alias="Book"></typeAlias>
</typeAliases>
  • plugins标签:用于配置MyBatis插件
<!--plugins标签,用于配置MyBatis插件(分页插件)-->
<plugins>
    <plugin interceptor=""></plugin>
</plugins>
  • environments标签:配置数据库连接信息
<!-- 在environments配置数据库连接信息 -->
<!-- 在environments标签中可以定义多个environment标签,每个environment标签可以定义一套连接配置 -->
<!-- default属性,用来指定使用哪个environment标签 -->
<environments default="mysql">

    <!--  environment 标签用于配置数据库连接信息  -->
    <environment id="mysql">

        <!--transactionManager标签用于配置数据库管理方式
            type="JDBC"  可以进行事务的提交和回滚操作
            type="MANAGED" 依赖容器完成事务管理,本身不进行事务的提交和回滚操作 -->
        <transactionManager type="JDBC"></transactionManager>

        <!--dataSource标签就是用来配置数据库连接信息 POOLED|UNPOOLED -->
        <dataSource type="POOLED">
            <property name="driver" value="${mysql_driver}"/>
            <property name="url" value="${mysql_url}"/>
            <property name="username" value="${mysql_username}"/>
            <property name="password" value="${mysql_password}"/>
        </dataSource>
    </environment>
</environments>
  • mappers标签:加载映射配置(映射文件、DAO注解)
<!--mappers标签用于载入映射文件-->
<mappers>
    <mapper resource="mappers/StudentMapper.xml"></mapper>
</mappers>

三、事务管理

SqlSession 对象:
1.getMapper(DAO.class) : 获取Mapper(DAO接口的实例)
2.事务管理

1. 手动提交事务

  • sqlSession.commit();提交事务
  • sqlSession.rollback();事务回滚

测试类中进行事务管理

@Test
public void insertStudent() {
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    //1.当我们获取sqlSession对象时,就默认开启了事务
    try{
        //通过会话获取DAO对象
        StudentDAO studentDAO = sqlSession.getMapper(StudentDAO.class);
        //测试StudentDAO中的方法
        Student student = new Student(0, "10005", "Lily", "女", 21);
        int i = studentDAO.insertStudent(student);
        //2.操作完成并成功之后,需要手动提交
        sqlSession.commit();
    }catch (Exception e){
        //3.当操作出现异常,调用rollback进行回滚
        sqlSession.rollback();
    }
}

业务逻辑层手动事务管理

public class StudentServiceImpl implements StudentService {

    public boolean addStudent(Student student) {
        boolean b = false;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            StudentDAO studentDAO = sqlSession.getMapper(StudentDAO.class);
            int i = studentDAO.insertStudent(student);
            b = i>0;
            sqlSession.commit();
        }catch (Exception e){
            sqlSession.rollback();
        }
        return b;
    }
}

2. 手动提交事务
通过SqlSessionFactory调用openSession方法获取SqlSession对象时,可以通过参数设置事务是否自动提交:

  • 如果参数设置为true,表示自定提交事务: factory.openSession(true);

  • 如果参数设置为false,或者不设置参数,表示手动提交:factory.openSession();/factory.openSession(false);

MyBatisUtil优化

public class MyBatisUtil {

    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> local = new ThreadLocal<SqlSession>();

    static{
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            factory = builder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getFactory(){
        return factory;
    }

    private static SqlSession getSqlSession(boolean isAutoCommit){
        SqlSession sqlSession = local.get();
        if(sqlSession == null ){
            sqlSession = factory.openSession(isAutoCommit);
            local.set(sqlSession);
        }
        return sqlSession;
    }

    //手动事务管理
    public static SqlSession getSqlSession(){
        return getSqlSession(false);
    }

    //自动事务提交
    public static <T extends Object>T getMapper(Class<T> c){
        SqlSession sqlSession = getSqlSession(true);
        return sqlSession.getMapper(c);
    }

}

业务逻辑层自动事务管理

public class StudentServiceImpl implements StudentService {

    private StudentDAO studentDAO = MyBatisUtil.getMapper(StudentDAO.class);

    public boolean addStudent(Student student) {
        int i = studentDAO.insertStudent(student);
        boolean b = i>0;
        return b;
    }
}

四、分页插件PageHelper

分页插件是一个独立于MyBatis框架之外的第三方插件

1.添加分页插件的依赖

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

2.配置插件
在mybatis的主配置文件mybatis-config.xml中通过plugins标签进行配置

<!--plugins标签,用于配置MyBatis插件(分页插件)-->
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>

3.分页实例
对学生信息进行分页查询

@Test
public void testListStudentsByPage() {
    StudentDAO studentDAO = MyBatisUtil.getMapper(StudentDAO.class); //sqlSession
    PageHelper.startPage(2,4);
    List<Student> students = studentDAO.listStudents();
    PageInfo<Student> pageInfo = new PageInfo<Student>(students);
    //pageInfo中就包含了数据及分页信息
}

带条件分页

@Test
public void testListStudentsByPage() {
    StudentDAO studentDAO = MyBatisUtil.getMapper(StudentDAO.class); //sqlSession
    PageHelper.startPage(2,4);
    //List<Student> students = studentDAO.listStudents();
    List<Student> list = studentDAO.listStudentsByGender("女");
    PageInfo<Student> pageInfo = new PageInfo<Student>(list);
    //pageInfo中就包含了数据及分页信息
}
参考链接:

https://www.bilibili.com/video/BV15Q4y1m78a?p=42

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值