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

5 篇文章 0 订阅
5 篇文章 1 订阅

动态SQL

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

  1. <if>是判断条件的
    语法
<if test- ”判断java对象的属性值">
部分sq1语句
</if>
  1. <where>用来包含多个的
    当多个if有-一个成立的,会 自动增加一一个whe re关键字,
    并去掉1f中多余的and,or等
  2. <foreach> 循环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:集合成员之间的分隔符

运行结果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码片段

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

接口方法:

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

mapper 文件:

<!--创建 sql 片段 id:片段的自定义名称-->
<sql id="studentSql">
 select id,name,email,age from student
</sql>
<select id="selectStudentSqlFragment" 
resultType="com.bjpowernode.domain.Student">
 <!-- 引用 sql 片段 -->
 <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 文件,需要在头部使用约束文件
<?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">

2.根元素
<configuration>
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 在初始化时,根据<dataSource>的 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 <transactionManager type="JDBC"/>该标签用于指定 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">
 <!--使用 properties 文件: 语法 ${key}-->
 <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 支持默认别名,我们也可以采用自定义别名方式来开发,主要使用在<select resultType=”别名”>
mybatis.xml 主配置文件定义别名:

<typeAliases>
 <!--
 定义单个类型的别名
 type:类型的全限定名称
 alias:自定义别名 
 -->

 <typeAlias type="com.bjpowernode.domain.Student" alias="mystudent"/>
 <!--
 批量定义别名,扫描整个包下的类,别名为类名(首字母大写或小写都可以)
 name:包名 
 -->
 <package name="com.bjpowernode.domain"/>
 <package name="...其他包"/>
</typeAliases>
mapper.xml 文件,使用别名表示类型
<select id="selectStudents" resultType="mystudent">
 select id,name,email,age from student
</select>

mappers(映射器)

(1) <mapper resource=" " />
使用相对于类路径的资源,从 classpath 路径查找文件
例如:<mapper resource="/dao/StudentDao.xml" />
(2)
指定包下的所有 Dao 接口
如:<package name="work01_mybatis_dao.content.domain.dao"/>

注意:此种方法要求 Dao 接口名称和 mapper 映射文件名称相同,且在同一个目录中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

之墨_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值