MyBatis框架—动态 SQL、配置文件、事务

MyBatis 框架动态 SQL、配置文件、事务

  • 动态SQL
    • 代码实现
      • 抽象类:
      • 测试方法:
      • Mapper映射:
      • 运行结果:
    • 代码片段
      • 接口方法:
      • mapper 文件:
      • 测试方法:
  • 配置文件
    • 主配置文件特点
    • dataSource 标签
    • dataSource 配置
  • 事务
      • 使用数据库属性配置文件
      • typeAliases(类型别名)
      • mappers(映射器)

动态SQL

动态sql:sql的内容是变化的,可以根据条件获取到不同sql语句。
主要是where部分发生变化
动态sql的实现:使用的是mybatis提供的标签, ,,

  1. 是判断条件的
    语法
<if test- ”判断java对象的属性值">
部分sq1语句
</if>
  1. 用来包含多个的
    当多个if有-一个成立的,会 自动增加一一个whe re关键字,
    并去掉1f中多余的and,or等
  2. 循环java中的数组,list集合的。主要用在sql的in语句中

代码实现

抽象类:

public interface StudentDao {
    //动态sql使用java对象作为参数
    List<Student> SelectStudentIf(Student student);
    //where的使用
    List<Student> SelectStudentWhere(Student student);
}

测试方法:

@Test
public void testSelectStudentIf(){
    Student student = new Student();
    student.setName("ChowRunFa");
    student.setAge(10);
    List<Student> students = studentDao.SelectStudentIf(student);
    for(Student stu:students){
        System.out.println("if==" + stu);
    }
}

@Test
public void testSelectStudentWhere(){
    Student student = new Student();
    student.setName("周润发");
    student.setAge(10);
    List<Student> students = studentDao.SelectStudentWhere(student);
    for(Student stu:students){
        System.out.println("where==" + stu);
    }
    
   @Test
    public void testSelectStudentWhere(){
        Student student = new Student();
        student.setName("周润发");
        student.setAge(10);
        List<Student> students = studentDao.SelectStudentWhere(student);
        for(Student stu:students){
            System.out.println("where==" + stu);
        }
    }

Mapper映射:

 <select id="SelectStudentIf" resultType="work01_mybatis_dao.content.domain.Student">
        select  id,name,age,email from students
        where
        <if test="name != null and name !=''">
            name = #{name}
        if>
        <if test="age > 0 ">
            or age > #{age}
        if>
    select>
    <select id="SelectStudentWhere" resultType="work01_mybatis_dao.content.domain.Student">
        select id,name,email,age from students
        <where>
            <if test="name != null and name != '' ">
                name  = #{name}
            if>
            <if test="age > 0">
                or age > #{age}
            if>
        where>
    <select id="SelectForEachOne" resultType="work01_mybatis_dao.content.domain.Student">
        select * from students where id in
          <foreach collection="list" item="stuid" open="(" close=")" separator=",">
                          #{stuid}
          foreach>
    select>

collection:表示按口中的方法鑫数的类型,如果是数组使用array,如果是list集合使用list
item:自定义的,表示教组和集合成员的变量
open:循环开始是的字符
close:循环结束时的字符
separator:集合成员之间的分隔符

运行结果:

MyBatis框架—动态 SQL、配置文件、事务_第1张图片
MyBatis框架—动态 SQL、配置文件、事务_第2张图片
MyBatis框架—动态 SQL、配置文件、事务_第3张图片

代码片段

标签用于定义 SQL 片断,以便其它 SQL 标签复用。而其它标签使用该 SQL 片断,需要使用
子标签。该标签可以定义 SQL 语句中的任何部分,所以子标签可以放在动态 SQL
的任何位置

接口方法:

List<Student> selectStudentSqlFragment(List<Student> stuList);

mapper 文件:


<sql id="studentSql">
 select id,name,email,age from student
sql>
<select id="selectStudentSqlFragment" 
resultType="com.bjpowernode.domain.Student">
 
 <include refid="studentSql"/>
 <if test="list !=null and list.size > 0 ">
 where id in
 <foreach collection="list" open="(" close=")" 
item="stuobject" separator=",">
 #{stuobject.id}
 foreach>
 if>
select>

测试方法:

@Test
public void testSelectSqlFragment() {
 List<Student> list = new ArrayList<>();
 Student s1 = new Student();
 s1.setId(1002);
 list.add(s1);
 s1 = new Student();
 s1.setId(1005);
 list.add(s1);
 List<Student> studentList = studentDao.selectStudentSqlFragment(list);
 studentList.forEach( stu -> System.out.println(stu));
}

配置文件

主配置文件特点

  1. xml 文件,需要在头部使用约束文件

DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">

2.根元素

3.主要包含内容:

  1. 定义别名
  2. 数据源
  3. mapper 文件

dataSource 标签

Mybatis 中访问数据库,可以连接池技术,但它采用的是自己的连接池技术。在 Mybatis 的 mybatis.xml
配置文件中,通过来实现 Mybatis 中连接池的配置

dataSource 配置

在 MyBatis.xml 主配置文件,配置 dataSource:

<dataSource type="POOLED">
 
 <property name="driver" value="com.mysql.jdbc.Driver"/>
 <property name="url" 
value="jdbc:mysql://localhost:3306/ssm?charset=utf-8"/>
 <property name="username" value="root"/>
 <property name="password" value="123456"/>
dataSource>

MyBatis 在初始化时,根据的 type 属性来创建相应类型的的数据源 DataSource,即:
type=”POOLED”:MyBatis 会创建 PooledDataSource 实例
type=”UNPOOLED” : MyBatis 会创建 UnpooledDataSource 实例
type=”JNDI”:MyBatis 会从 JNDI 服务上查找 DataSource 实例,然后返回使用

事务

默认需要手动提交事务

Mybatis 框架是对 JDBC 的封装,所以 Mybatis 框架的事务控制方式,本身也是用 JDBC 的 Connection对象的
commit(), rollback() . Connection 对象的
setAutoCommit()方法来设置事务提交方式的。
自动提交和手工提交

html 该标签用于指定 MyBatis所使用的事务管理器
MyBatis 支持两种事务管理器类型:JDBC 与 MANAGED

JDBC:

使用 JDBC 的事务管理机制。即通过 Connection 的 commit()方法提交,通过
rollback()方法回滚。但默认情况下,MyBatis
将自动提交功能关闭了,改为了手动提交。即程序中需要显式的对事务进行提交或回滚。从日志的输出信息中可以看到。
MANAGED:由容器来管理事务的整个生命周期(如 Spring 容器)

自动提交事务

设置自动提交的方式,factory 的 openSession() 分为有参数和无参数的。 有参数为 true,使用自动提交,可以修改
MyBatisUtil 的 getSqlSession()方法。 session = factory.openSession(true);
再执行 insert 操作,无需执行 session.commit(),事务是自动提交的

使用数据库属性配置文件

为 了方便对数据库连接的管理,DB连接四要素数据一般都是存放在一个专门的属性文件中的。MyBatis主配置文件需要从这个属性文件中读取这些数据

步骤:

  1. 在 classpath 路径下,创建 properties 文件
    在 resources 目录创建 jdbc.properties 文件,文件名称自定义。
  2. 使用 properties 标签
    修改主配置文件,文件开始位置加入:
  3. 使用 key 指定值
<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>

typeAliases(类型别名)

Mybatis 支持默认别名,我们也可以采用自定义别名方式来开发,主要使用在