盤錦做網(wǎng)站公司百度推廣登錄后臺登錄入口
前面我們介紹了Mybatis動態(tài)SQL的使用;本篇我們介紹使用mybatis- freemarker動態(tài)語言生成動態(tài)SQL。
如果您對Mybatis動態(tài)SQL不太了解,建議您先進(jìn)行了解后再閱讀本篇,可以參考:
Mybatis 動態(tài)SQL – 使用if,where標(biāo)簽動態(tài)生成條件語句
Mybatis 動態(tài)SQL – 使用if,set標(biāo)簽動態(tài)生成更新語句
Mybatis 動態(tài)SQL – 使用choose標(biāo)簽動態(tài)生成條件語句
Mybatis 動態(tài)SQL – 使用choose標(biāo)簽動態(tài)生成更新語句
Mybatis 動態(tài)SQL – 使用trim標(biāo)簽替代where,set標(biāo)簽
Mybatis 動態(tài)SQL - 使用foreach標(biāo)簽查詢數(shù)據(jù)、批量新增、批量修改、刪除數(shù)據(jù)
一、數(shù)據(jù)準(zhǔn)備
這里我們直接使用腳本初始化數(shù)據(jù)庫中的數(shù)據(jù)
-- 如果數(shù)據(jù)庫不存在則創(chuàng)建數(shù)據(jù)庫
CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
-- 切換數(shù)據(jù)庫
USE demo;
-- 創(chuàng)建用戶表
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 '學(xué)歷(ZK:??? BK:本科, YJS:研究生, BS:博士)'
);
-- 插入用戶數(shù)據(jù)
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');
創(chuàng)建了一個名稱為demo的數(shù)據(jù)庫;并在庫里創(chuàng)建了名稱為T_TEACHER的教師表并向表中插入了數(shù)據(jù)
二、環(huán)境準(zhǔn)備
1、添加依賴
<dependency><groupId>org.mybatis.scripting</groupId><artifactId>mybatis-freemarker</artifactId><version>1.2.4</version>
</dependency>
2、創(chuàng)建實(shí)體類
在cn.horse.demo下創(chuàng)建TeacherInfo、TeacherInfoQuery實(shí)體類:
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;}@Overridepublic 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 mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.horse.demo.TeacherInfoMapper"></mapper>
4、動態(tài)語言配置
在resources下新建mybatis-config.xml配置文件,配置freemarker默認(rèn)的腳本語言,并引入TeacherInfoMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//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.freemarker.FreeMarkerLanguageDriver"/></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><mappers><mapper resource="demo/TeacherInfoMapper.xml" /></mappers>
</configuration>
其中<setting name="defaultScriptingLanguage" value="org.mybatis.scripting.freemarker.FreeMarkerLanguageDriver"/>用于配置freemarker作為默認(rèn)的動態(tài)語言
5、日志配置
在resources的目錄下新建logging.properties配置文件
handlers=java.util.logging.ConsoleHandler
.level=INFOcn.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");// 根據(jù)配置創(chuàng)建SqlSession工廠sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}/*** 開啟會話* @return*/public static SqlSession openSession() {return sqlSessionFactory.openSession();}/*** 關(guān)閉會話* @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);}}
}
三、查詢數(shù)據(jù)
在TeacherInfoMapper.xml配置文件中新增findByQuery查詢語句:
<select id="find" resultType="cn.horse.demo.TeacherInfo">SELECTID,TEACHER_NAME name,DEPARTMENT,BIRTH,DEGREEFROM T_TEACHERWHERE 1 = 1<![CDATA[<#if degree?? && '' != degree>AND DEGREE = <@p name='degree'/></#if><#if department?? && '' != department>AND DEPARTMENT = <@p name='department'/></#if>]]>
</select>
#if類似于<if>標(biāo)簽,第一個標(biāo)簽代表的是degree不為null并且不為空字符串,第二個標(biāo)簽代表的是department不為null并且不為空字符串;
測試:
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");// 查詢學(xué)歷為本科的教師
TeacherInfoQuery query = new TeacherInfoQuery();
query.setDegree("BK");
find("cn.horse.demo.TeacherInfoMapper.find", query);
執(zhí)行后的結(jié)果如下:
四、批量插入數(shù)據(jù)
在TeacherInfoMapper.xml配置文件中新增insert插入語句:
<insert id="insert">INSERT INTO T_TEACHER(ID, TEACHER_NAME, DEPARTMENT, BIRTH, DEGREE)VALUES<![CDATA[<#list list as teacherInfo>(<@p value=teacherInfo.id/>,<@p value=teacherInfo.name/>,<@p value=teacherInfo.department/>,<@p value=teacherInfo.birth/>,<@p value=teacherInfo.degree/>)<#if teacherInfo_has_next>,</#if></#list>]]>
</insert>
測試:
// 引入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);
執(zhí)行的結(jié)果如下:
五、更新數(shù)據(jù)
在TeacherInfoMapper.xml配置文件中新增update更新語句:
<update id="update">UPDATE T_TEACHERSET<![CDATA[ID = <@p name='id'/><#if name?? && '' != name>, TEACHER_NAME = <@p name='name'/></#if><#if department?? && '' != department>, DEPARTMENT = <@p name='department'/></#if><#if birth??>, BIRTH = <@p name='birth'/></#if><#if degree?? && '' != degree>, DEGREE = <@p name='degree'/></#if>]]>WHERE ID = <![CDATA[ <@p name='id'/> ]]>
</update>
測試:
// 引入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);
執(zhí)行的結(jié)果如下:
六、批量刪除數(shù)據(jù)
在TeacherInfoMapper.xml配置文件中新增delete刪除語句:
<delete id="delete">DELETE FROM T_TEACHERWHERE ID IN (<![CDATA[<#list list as id><@p value=id/><#if id_has_next>,</#if></#list>]]>)
</delete>
測試:
// 引入JDK日志配置
System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");delete("cn.horse.demo.TeacherInfoMapper.delete", Arrays.asList(11, 12));
執(zhí)行的結(jié)果如下: