前面我们介绍了Mybatis动态SQL的使用;本篇我们介绍使用mybatis-velocity动态语言生成动态SQL。
如果您对Mybatis动态SQL不太了解,建议您先进行了解后再阅读本篇,可以参考:
Mybatis 动态SQL – 使用if,where标签动态生成条件语句
Mybatis 动态SQL – 使用if,set标签动态生成更新语句
Mybatis 动态SQL – 使用choose标签动态生成条件语句
Mybatis 动态SQL – 使用choose标签动态生成更新语句
Mybatis 动态SQL - 使用foreach标签查询数据、批量新增、批量修改、删除数据
一、数据准备
这里我们直接使用脚本初始化数据库中的数据
-- 如果数据库不存在则创建数据库
CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
-- 切换数据库
USE demo;
-- 创建用户表
CREATE TABLE IF NOT EXISTS T_TEACHER(
ID INT PRIMARY KEY COMMENT '教师编号',
TEACHER_NAME VARCHAR(64) NOT NULL COMMENT '教师名称',
DEPARTMENT VARCHAR(16) NOT NULL COMMENT '所属部门',
BIRTH DATE NOT NULL COMMENT '出生年月',
DEGREE VARCHAR(16) NOT NULL COMMENT '学历(ZK:专科, BK:本科, YJS:研究生, BS:博士)'
);
-- 插入用户数据
INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)
VALUES(1, '张三1', '001', '1990-06-12', 'BK'),
(2, '李四1', '002', '1992-05-10', 'BK'),
(3, '张三2', '003', '1988-01-15', 'YJS'),
(4, '李四2', '001', '1979-03-10', 'BK'),
(5, '李四3', '003', '1995-08-16', 'YJS');
创建了一个名称为demo的数据库;并在库里创建了名称为T_TEACHER的教师表并向表中插入了数据
二、环境准备
1、添加依赖
<dependency>
<groupId>org.mybatis.scripting</groupId>
<artifactId>mybatis-velocity</artifactId>
<version>2.1.0</version>
</dependency>
2、创建实体类
在cn.horse.demo下创建TeacherInfo、TeacherInfoQuery实体类:
TeacherInfo类:
package cn.horse.demo;
import java.time.LocalDate;
public class TeacherInfo {
private Integer id;
private String name;
private String department;
private LocalDate birth;
private String degree;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setDepartment(String department) {
this.department = department;
}
public String getDepartment() {
return department;
}
public void setBirth(LocalDate birth) {
this.birth = birth;
}
public LocalDate getBirth() {
return birth;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getDegree() {
return degree;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{ ");
stringBuilder.append("id: ");
stringBuilder.append(this.id);
stringBuilder.append(", ");
stringBuilder.append("name: ");
stringBuilder.append(this.name);
stringBuilder.append(", ");
stringBuilder.append("department: ");
stringBuilder.append(this.department);
stringBuilder.append(", ");
stringBuilder.append("birth: ");
stringBuilder.append(this.birth);
stringBuilder.append(", ");
stringBuilder.append("degree: ");
stringBuilder.append(this.degree);
stringBuilder.append(" }");
return stringBuilder.toString();
}
}
TeacherInfoQuery类:
package cn.horse.demo;
public class TeacherInfoQuery {
private String department;
private String degree;
public void setDepartment(String department) {
this.department = department;
}
public String getDepartment() {
return department;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getDegree() {
return degree;
}
}
3、Mapper配置文件
在resources的目录下新建TeacherInfoMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.horse.demo.TeacherInfoMapper">
</mapper>
4、动态语言配置
在resources下新建mybatis-config.xml配置文件,配置velocity默认的脚本语言,并引入TeacherInfoMapper.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>
<settings>
<setting name="logImpl" value="JDK_LOGGING"/>
<setting name="defaultScriptingLanguage" value="org.mybatis.scripting.velocity.VelocityLanguageDriver"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="horse"/>
</dataSource>
</environment>
</environments>
</configuration>
其中<setting name="defaultScriptingLanguage" value="org.mybatis.scripting.velocity.VelocityLanguageDriver"/>用于配置velocity作为默认的动态语言
5、日志配置
在resources的目录下新建logging.properties配置文件
handlers=java.util.logging.ConsoleHandler
.level=INFO
cn.horse.demo.TeacherInfoMapper.level=FINER
java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tT.%1$tL %4$s %3$s - %5$s%6$s%n
在cn.horse.demo下新建JdkLogConfig类:
JdkLogConfig类:
package cn.horse.demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;
public class JdkLogConfig {
public JdkLogConfig() {
try {
InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("logging.properties");
LogManager.getLogManager().readConfiguration(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
6、会话工具类
在cn.horse.demo包下新建SqlSessionUtils工具类
package cn.horse.demo;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.Objects;
public class SqlSessionUtils {
private static final SqlSessionFactory sqlSessionFactory;
static {
// 读取mybatis配置文件
InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
// 根据配置创建SqlSession工厂
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
}
/**
* 开启会话
* @return
*/
public static SqlSession openSession() {
return sqlSessionFactory.openSession();
}
/**
* 关闭会话
* @param sqlSession
*/
public static void closeSession(SqlSession sqlSession) {
if(Objects.nonNull(sqlSession)) {
sqlSession.close();
}
}
}
7、启动程序配置
package cn.horse.demo;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
}
private static void find(String statement, TeacherInfoQuery query) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
List<TeacherInfo> teacherInfoList = sqlSession.selectList(statement, query);
for (TeacherInfo teacherInfo: teacherInfoList) {
System.out.println(teacherInfo);
}
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
private static void insert(String statement, List<TeacherInfo> teacherInfoList) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
sqlSession.insert(statement, teacherInfoList);
sqlSession.commit();
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
private static void update(String statement, TeacherInfo teacherInfo) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
sqlSession.update(statement, teacherInfo);
sqlSession.commit();
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
private static void delete(String statement, List<Integer> idList) {
SqlSession sqlSession = null;
try {
sqlSession = SqlSessionUtils.openSession();
sqlSession.delete(statement, idList);
sqlSession.commit();
} finally {
SqlSessionUtils.closeSession(sqlSession);
}
}
}
启动程序中,我们提供了新增、删除、修改、查询等方法,用于测试使用
三、查询数据
在TeacherInfoMapper.xml配置文件中新增findByQuery查询语句:
<select id="find" resultType="cn.horse.demo.TeacherInfo">
SELECT
ID,
TEACHER_NAME name,
DEPARTMENT,
BIRTH,
DEGREE
FROM T_TEACHER
#where()
#if($_parameter.degree and '' != $_parameter.degree)
AND DEGREE = @{_parameter.degree}
#end
#if($_parameter.department and '' != $_parameter.department)
AND DEPARTMENT = @{_parameter.department}
#end
#end
</select>
#where()类似于<where>标签;
#if()类似于<if>标签,第一个标签代表的是degree不为null并且不为空字符串,第二个标签代表的是department不为null并且不为空字符串;
取参数值时使用
$_parameter.参数名
格式,例如:我们获取degree参数值时使用$_parameter.degree
预处理参数使用
@{_parameter.参数名}
格式,例如:我们预处理degree参数时使用@{_parameter.degree}
测试:
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
// 查询学历为本科的教师
TeacherInfoQuery query = new TeacherInfoQuery();
query.setDegree("BK");
find("cn.horse.demo.TeacherInfoMapper.find", query);
执行后的结果如下:
四、批量插入数据
在TeacherInfoMapper.xml配置文件中新增insert插入语句:
<insert id="insert">
INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)
#repeat($_parameter.list $teacherInfo "," "VALUES " "")
(@{teacherInfo.id}, @{teacherInfo.name}, @{teacherInfo.department}, @{teacherInfo.birth}, @{teacherInfo.degree})
#end
</insert>
#repeat类似于<foreach>标签,其格式为
#repeat(collection var separator open close)
#end
collection:数组或可迭代对象
var:数组中的元素或本次迭代的元素
separator:迭代之间的分隔符
open:指定开头的字符串
close:指定结尾的字符串
测试:
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
List<TeacherInfo> teacherInfoList = new ArrayList<>();
TeacherInfo teacherInfo1 = new TeacherInfo();
teacherInfo1.setId(11);
teacherInfo1.setName("张三11");
teacherInfo1.setDepartment("001");
teacherInfo1.setBirth(LocalDate.of(1988, 5, 20));
teacherInfo1.setDegree("BK");
teacherInfoList.add(teacherInfo1);
TeacherInfo teacherInfo2 = new TeacherInfo();
teacherInfo2.setId(12);
teacherInfo2.setName("李四12");
teacherInfo2.setDepartment("003");
teacherInfo2.setBirth(LocalDate.of(1989, 8, 10));
teacherInfo2.setDegree("ZK");
teacherInfoList.add(teacherInfo2);
insert("cn.horse.demo.TeacherInfoMapper.insert", teacherInfoList);
执行的结果如下:
五、更新数据
在TeacherInfoMapper.xml配置文件中新增update更新语句:
<update id="update">
UPDATE T_TEACHER
#mset()
#if($_parameter.name and '' != $_parameter.name)
TEACHER_NAME = @{_parameter.name},
#end
#if($_parameter.department and '' != $_parameter.department)
DEPARTMENT = @{_parameter.department},
#end
#if($_parameter.birth)
BIRTH = @{_parameter.birth},
#end
#if($_parameter.degree and '' != $_parameter.degree)
DEGREE = @{_parameter.degree},
#end
#end
WHERE ID = @{_parameter.id}
</update>
#mset类似于<set>标签
测试:
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
TeacherInfo teacherInfo = new TeacherInfo();
teacherInfo.setId(11);
teacherInfo.setName("张三22");
update("cn.horse.demo.TeacherInfoMapper.update", teacherInfo);
执行的结果如下:
六、批量删除数据
在TeacherInfoMapper.xml配置文件中新增delete删除语句:
<delete id="delete">
DELETE FROM T_TEACHER
WHERE ID IN
#repeat($_parameter.list $id "," "(" ")")
@{id}
#end
</delete>
测试:
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
delete("cn.horse.demo.TeacherInfoMapper.delete", Arrays.asList(11, 12));
执行的结果如下: