Mybatis如何構建SQL語句
SQL構建對象介紹
我們之前通過注解開發(fā)時,相關 SQL 語句都是自己直接拼寫的。
一些關鍵字寫起來比較麻煩、而且容易出錯。
MyBatis 給我們提供了 org.apache.ibatis.jdbc.SQL 功能類,專門用于構建 SQL 語句。
就是使用方法調用來代替之前繁瑣的SQL編寫。
我們來使用一下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; } }
再查看一下它的父類
顯然,這些大家都應該很熟悉,都是SQL中的關鍵字,使用SQL功能類,可以降低在開發(fā)中的出錯率。
查詢功能的實現(xiàn)
定義功能類并提供獲取查詢的 SQL 語句的方法。
@SelectProvider:生成查詢用的 SQL 語句注解。
- type 屬性:生成 SQL 語句功能類對象
- method 屬性:指定調用方法
ReturnSql類
這里面創(chuàng)建SQL的功能類
public class ReturnSql { // 定義方法,返回用來查詢的SQL語句 public String getSelectAll() { return new SQL() { { SELECT("*"); FROM("student"); } }.toString(); } }
StudentMapper類
public interface StudentMapper { // 查詢全部 //@Select("SELECT * FROM student") @SelectProvider(type = ReturnSql.class, method = "getSelectAll") public abstract List<Student> selectAll(); };
這里的type的值就是生成 SQL 語句功能類對象——ReturnSql,method的值就是功能類中的方法
——getSelectAll
Test類
public class Test01 { @Test public void selectAll() throws IOException { // 1.加載核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); // 2.獲取SqlSession工廠對象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3.通過工廠對象獲取SqlSession對象 SqlSession sqlSession = sqlSessionFactory.openSession(true); // 4.獲取StudentMapper接口的實現(xiàn)類對象 // 通過StudentMapper的字節(jié)對象 來得到實現(xiàn)類對象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // 5.調用實現(xiàn)類對象中的方法 List<Student> list = mapper.selectAll(); // 6.處理結果 for (Student student : list) { System.out.println(student); } // 7.釋放資源 sqlSession.close(); is.close(); } }
新增、修改、刪除功能的實現(xiàn)
其實這些都是大同小異,比起之前的Mybatis框架前面的學習不值一提,只要調用函數(shù)就可以實現(xiàn)。
- @InsertProvider:生成新增用的 SQL 語句注解。
- @UpdateProvider:生成修改用的 SQL 語句注解。
- @DeleteProvider:生成刪除用的 SQL 語句注解。
完整代碼展現(xiàn)
項目骨架
bean包下的Student類
映射配置文件StudentMapper接口
我們使用注解的方式將SQL工具類引入
public interface StudentMapper { // 查詢全部 //@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類
里面編寫了SQL功能類
public class ReturnSql { // 定義方法,返回用來查詢的SQL語句 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(); } }
測試方法
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工廠對象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3.通過工廠對象獲取SqlSession對象 SqlSession sqlSession = sqlSessionFactory.openSession(true); // 4.獲取StudentMapper接口的實現(xiàn)類對象 // 通過StudentMapper的字節(jié)對象 來得到實現(xiàn)類對象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // 5.調用實現(xiàn)類對象中的方法 List<Student> list = mapper.selectAll(); // 6.處理結果 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工廠對象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3.通過工廠對象獲取SqlSession對象 SqlSession sqlSession = sqlSessionFactory.openSession(true); // 4.獲取StudentMapper接口的實現(xiàn)類對象 // 通過StudentMapper的字節(jié)對象 來得到實現(xiàn)類對象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // 5.調用實現(xiàn)類對象中的方法 Student stu = new Student(9,"張九",90); Integer result = mapper.insert(stu); // 6.處理結果 System.out.println(result); // 7.釋放資源 sqlSession.close(); is.close(); } @Test public void update() throws IOException { // 1.加載核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); // 2.獲取SqlSession工廠對象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3.通過工廠對象獲取SqlSession對象 SqlSession sqlSession = sqlSessionFactory.openSession(true); // 4.獲取StudentMapper接口的實現(xiàn)類對象 // 通過StudentMapper的字節(jié)對象 來得到實現(xiàn)類對象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // 5.調用實現(xiàn)類對象中的方法 Student stu = new Student(9,"張九",1000); Integer result = mapper.update(stu); // 6.處理結果 System.out.println(result); // 7.釋放資源 sqlSession.close(); is.close(); } @Test public void delete() throws IOException { // 1.加載核心配置文件 InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); // 2.獲取SqlSession工廠對象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); // 3.通過工廠對象獲取SqlSession對象 SqlSession sqlSession = sqlSessionFactory.openSession(true); // 4.獲取StudentMapper接口的實現(xiàn)類對象 // 通過StudentMapper的字節(jié)對象 來得到實現(xiàn)類對象 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); // 5.調用實現(xiàn)類對象中的方法 Integer result = mapper.delete(9); // 6.處理結果 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 核心根標簽--> <configuration> <!-- 引入數(shù)據(jù)庫連接的配置文件 --> <properties resource="jdbc.properties"/> <!-- 配置log4j --> <settings> <setting name="logImpl" value="log4j"/> </settings> <!-- 使用通用的配置方式起別名 ,別名默認是類名 --> <typeAliases> <package name="com.itheima.bean"/> </typeAliases> <!--environments配置數(shù)據(jù)庫環(huán)境,環(huán)境可以有多個。default屬性指定使用的是哪個--> <environments default="mysql"> <!--environment配置數(shù)據(jù)庫環(huán)境 id屬性唯一標識--> <environment id="mysql"> <!-- transactionManager事務管理。 type屬性,采用JDBC默認的事務--> <transactionManager type="JDBC"/> <!-- dataSource數(shù)據(jù)源信息 type屬性 連接池--> <dataSource type="POOLED"> <!-- property獲取數(shù)據(jù)庫連接的配置信息 --> <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屬性用來指定包的路徑--> <package name="com.itheima.mapper"/> </mappers> </configuration>
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
使用@Service注解出現(xiàn)No bean named 'xxxx'&
這篇文章主要介紹了使用@Service注解出現(xiàn)No bean named 'xxxx' available]錯誤的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08Springboot PostMapping無法獲取數(shù)據(jù)問題及解決
這篇文章主要介紹了Springboot PostMapping無法獲取數(shù)據(jù)問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05java中CompletableFuture異步執(zhí)行方法
本文主要介紹了java中CompletableFuture異步執(zhí)行方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06MyBatis不同Mapper文件引用resultMap實例代碼
這篇文章主要介紹了mybatis 不同Mapper文件引用resultMap的實例代碼,非常不錯具有參考借鑒價值,需要的朋友可以參考下2017-07-07