Mybatis如何構(gòu)建SQL語(yǔ)句
SQL構(gòu)建對(duì)象介紹
我們之前通過(guò)注解開(kāi)發(fā)時(shí),相關(guān) SQL 語(yǔ)句都是自己直接拼寫(xiě)的。
一些關(guān)鍵字寫(xiě)起來(lái)比較麻煩、而且容易出錯(cuò)。
MyBatis 給我們提供了 org.apache.ibatis.jdbc.SQL 功能類,專門(mén)用于構(gòu)建 SQL 語(yǔ)句。

就是使用方法調(diào)用來(lái)代替之前繁瑣的SQL編寫(xiě)。
我們來(lái)使用一下Mybatis提供的SQL功能類
package com.itheima.sql;
import org.apache.ibatis.jdbc.SQL;
public class sqlTest {
public static void main(String[] args) {
String sql = getSql();
System.out.println(sql);
// 輸出
// SELECT *
// FROM student
}
public static String getSql() {
String sql = new SQL() {
{
SELECT("*");
FROM("student");
}
}.toString();
return sql;
}
}我們可以查看一下SQL功能類
package org.apache.ibatis.jdbc;
public class SQL extends AbstractSQL<SQL> {
public SQL() {
}
public SQL getSelf() {
return this;
}
}再查看一下它的父類

顯然,這些大家都應(yīng)該很熟悉,都是SQL中的關(guān)鍵字,使用SQL功能類,可以降低在開(kāi)發(fā)中的出錯(cuò)率。
查詢功能的實(shí)現(xiàn)
定義功能類并提供獲取查詢的 SQL 語(yǔ)句的方法。
@SelectProvider:生成查詢用的 SQL 語(yǔ)句注解。
- type 屬性:生成 SQL 語(yǔ)句功能類對(duì)象
- method 屬性:指定調(diào)用方法
ReturnSql類
這里面創(chuàng)建SQL的功能類
public class ReturnSql {
// 定義方法,返回用來(lái)查詢的SQL語(yǔ)句
public String getSelectAll() {
return new SQL() {
{
SELECT("*");
FROM("student");
}
}.toString();
}
}StudentMapper類
public interface StudentMapper {
// 查詢?nèi)?
//@Select("SELECT * FROM student")
@SelectProvider(type = ReturnSql.class, method = "getSelectAll")
public abstract List<Student> selectAll();
};這里的type的值就是生成 SQL 語(yǔ)句功能類對(duì)象——ReturnSql,method的值就是功能類中的方法
——getSelectAll
Test類
public class Test01 {
@Test
public void selectAll() throws IOException {
// 1.加載核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.獲取SqlSession工廠對(duì)象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.通過(guò)工廠對(duì)象獲取SqlSession對(duì)象
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 4.獲取StudentMapper接口的實(shí)現(xiàn)類對(duì)象
// 通過(guò)StudentMapper的字節(jié)對(duì)象 來(lái)得到實(shí)現(xiàn)類對(duì)象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 5.調(diào)用實(shí)現(xiàn)類對(duì)象中的方法
List<Student> list = mapper.selectAll();
// 6.處理結(jié)果
for (Student student : list) {
System.out.println(student);
}
// 7.釋放資源
sqlSession.close();
is.close();
}
}
新增、修改、刪除功能的實(shí)現(xiàn)
其實(shí)這些都是大同小異,比起之前的Mybatis框架前面的學(xué)習(xí)不值一提,只要調(diào)用函數(shù)就可以實(shí)現(xiàn)。
- @InsertProvider:生成新增用的 SQL 語(yǔ)句注解。
- @UpdateProvider:生成修改用的 SQL 語(yǔ)句注解。
- @DeleteProvider:生成刪除用的 SQL 語(yǔ)句注解。
完整代碼展現(xiàn)
項(xiàng)目骨架

bean包下的Student類

映射配置文件StudentMapper接口
我們使用注解的方式將SQL工具類引入
public interface StudentMapper {
// 查詢?nèi)?
//@Select("SELECT * FROM student")
@SelectProvider(type = ReturnSql.class, method = "getSelectAll")
public abstract List<Student> selectAll();
// 新增操作
//@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
@InsertProvider(type = ReturnSql.class, method = "getInsert")
public abstract Integer insert(Student stu);
// 修改操作
//@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
@UpdateProvider(type = ReturnSql.class, method = "getUpdate")
public abstract Integer update(Student stu);
// 刪除操作
//@Delete("DELETE FROM student WHERE id=#{id}")
@DeleteProvider(type = ReturnSql.class, method = "getDelete")
public abstract Integer delete(Integer id);
}sql包下的ReturnSql類
里面編寫(xiě)了SQL功能類
public class ReturnSql {
// 定義方法,返回用來(lái)查詢的SQL語(yǔ)句
public String getSelectAll() {
return new SQL() {
{
SELECT("*");
FROM("student");
}
}.toString();
}
public String getInsert(Student stu) {
return new SQL() {
{
INSERT_INTO("student");
INTO_VALUES("#{id},#{name},#{age}");
}
}.toString();
}
public String getUpdate(Student stu) {
return new SQL() {
{
UPDATE("student");
SET("name=#{name}","age=#{age}");
WHERE("id=#{id}");
}
}.toString();
}
public String getDelete(Integer id) {
return new SQL() {
{
DELETE_FROM("student");
WHERE("id=#{id}");
}
}.toString();
}
}測(cè)試方法
package com.itheima.test;
import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test01 {
@Test
public void selectAll() throws IOException {
// 1.加載核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.獲取SqlSession工廠對(duì)象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.通過(guò)工廠對(duì)象獲取SqlSession對(duì)象
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 4.獲取StudentMapper接口的實(shí)現(xiàn)類對(duì)象
// 通過(guò)StudentMapper的字節(jié)對(duì)象 來(lái)得到實(shí)現(xiàn)類對(duì)象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 5.調(diào)用實(shí)現(xiàn)類對(duì)象中的方法
List<Student> list = mapper.selectAll();
// 6.處理結(jié)果
for (Student student : list) {
System.out.println(student);
}
// 7.釋放資源
sqlSession.close();
is.close();
}
@Test
public void insert() throws IOException {
// 1.加載核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.獲取SqlSession工廠對(duì)象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.通過(guò)工廠對(duì)象獲取SqlSession對(duì)象
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 4.獲取StudentMapper接口的實(shí)現(xiàn)類對(duì)象
// 通過(guò)StudentMapper的字節(jié)對(duì)象 來(lái)得到實(shí)現(xiàn)類對(duì)象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 5.調(diào)用實(shí)現(xiàn)類對(duì)象中的方法
Student stu = new Student(9,"張九",90);
Integer result = mapper.insert(stu);
// 6.處理結(jié)果
System.out.println(result);
// 7.釋放資源
sqlSession.close();
is.close();
}
@Test
public void update() throws IOException {
// 1.加載核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.獲取SqlSession工廠對(duì)象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.通過(guò)工廠對(duì)象獲取SqlSession對(duì)象
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 4.獲取StudentMapper接口的實(shí)現(xiàn)類對(duì)象
// 通過(guò)StudentMapper的字節(jié)對(duì)象 來(lái)得到實(shí)現(xiàn)類對(duì)象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 5.調(diào)用實(shí)現(xiàn)類對(duì)象中的方法
Student stu = new Student(9,"張九",1000);
Integer result = mapper.update(stu);
// 6.處理結(jié)果
System.out.println(result);
// 7.釋放資源
sqlSession.close();
is.close();
}
@Test
public void delete() throws IOException {
// 1.加載核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 2.獲取SqlSession工廠對(duì)象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
// 3.通過(guò)工廠對(duì)象獲取SqlSession對(duì)象
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 4.獲取StudentMapper接口的實(shí)現(xiàn)類對(duì)象
// 通過(guò)StudentMapper的字節(jié)對(duì)象 來(lái)得到實(shí)現(xiàn)類對(duì)象
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 5.調(diào)用實(shí)現(xiàn)類對(duì)象中的方法
Integer result = mapper.delete(9);
// 6.處理結(jié)果
System.out.println(result);
// 7.釋放資源
sqlSession.close();
is.close();
}
}隨便附上核心配置文件MyBatisConfig.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 核心根標(biāo)簽-->
<configuration>
<!-- 引入數(shù)據(jù)庫(kù)連接的配置文件 -->
<properties resource="jdbc.properties"/>
<!-- 配置log4j -->
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
<!-- 使用通用的配置方式起別名 ,別名默認(rèn)是類名 -->
<typeAliases>
<package name="com.itheima.bean"/>
</typeAliases>
<!--environments配置數(shù)據(jù)庫(kù)環(huán)境,環(huán)境可以有多個(gè)。default屬性指定使用的是哪個(gè)-->
<environments default="mysql">
<!--environment配置數(shù)據(jù)庫(kù)環(huán)境 id屬性唯一標(biāo)識(shí)-->
<environment id="mysql">
<!-- transactionManager事務(wù)管理。 type屬性,采用JDBC默認(rèn)的事務(wù)-->
<transactionManager type="JDBC"/>
<!-- dataSource數(shù)據(jù)源信息 type屬性 連接池-->
<dataSource type="POOLED">
<!-- property獲取數(shù)據(jù)庫(kù)連接的配置信息 -->
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!-- mappers引入映射配置文件 -->
<mappers>
<!-- mapper 引入指定的映射配置文件 resource屬性指定映射配置文件的名稱 -->
<!-- package 的name屬性用來(lái)指定包的路徑-->
<package name="com.itheima.mapper"/>
</mappers>
</configuration>
總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringMVC中ModelAndView的使用及說(shuō)明
這篇文章主要介紹了SpringMVC中ModelAndView的使用及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
使用@Service注解出現(xiàn)No bean named 'xxxx'&
這篇文章主要介紹了使用@Service注解出現(xiàn)No bean named 'xxxx' available]錯(cuò)誤的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
Springboot PostMapping無(wú)法獲取數(shù)據(jù)問(wèn)題及解決
這篇文章主要介紹了Springboot PostMapping無(wú)法獲取數(shù)據(jù)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
java中CompletableFuture異步執(zhí)行方法
本文主要介紹了java中CompletableFuture異步執(zhí)行方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
MyBatis不同Mapper文件引用resultMap實(shí)例代碼
這篇文章主要介紹了mybatis 不同Mapper文件引用resultMap的實(shí)例代碼,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2017-07-07

