Mybatis构建sql语法
生活随笔
收集整理的這篇文章主要介紹了
Mybatis构建sql语法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
構建sql:
- 之前通過注解開發時,相關 SQL 語句都是自己直接拼寫的。一些關鍵字寫起來比較麻煩、而且容易出錯。
- MyBatis 給我們提供了 org.apache.ibatis.jdbc.SQL 功能類,專門用于構建 SQL 語句
常用方法:
查詢功能的實現:
- @SelectProvider:生成查詢用的 SQL語句注解
- type 屬性:生成 SQL 語句功能類對象
- method 屬性:指定調用方法
新增功能的實現:
- @InsertProvider:生成新增用的 SQL 語句注解。
- type 屬性:生成 SQL 語句功能類對象
- method 屬性:指定調用方法
修改功能的實現:
- @UpdateProvider:生成修改用的 SQL 語句注解。
- type 屬性:生成 SQL 語句功能類對象
- method 屬性:指定調用方法
刪除功能的實現:
- @DeleteProvider:生成刪除用的 SQL 語句注解
- type 屬性:生成 SQL 語句功能類對象
- method 屬性:指定調用方法
演示:
SQL類:
public class ReturnSql {//定義方法,返回查詢的sql語句public String getSelectAll() {return new SQL() {{SELECT("*");FROM("student");}}.toString();}//定義方法,返回新增的sql語句public String getInsert(Student stu) {return new SQL() {{INSERT_INTO("student");INTO_VALUES("#{id},#{name},#{age}");}}.toString();}//定義方法,返回修改的sql語句public String getUpdate(Student stu) {return new SQL() {{UPDATE("student");SET("name=#{name}","age=#{age}");WHERE("id=#{id}");}}.toString();}//定義方法,返回刪除的sql語句public String getDelete(Integer id) {return new SQL() {{DELETE_FROM("student");WHERE("id=#{id}");}}.toString();} }接口:
public interface PersonMapper {//查詢全部//@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); }測試:
@Testpublic void selectAll() throws Exception {//1.加載核心配置文件InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");//2.獲取SqlSession工廠對象SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//3.通過工廠對象獲取SqlSession對象SqlSession sqlSession = sqlSessionFactory.openSession(true);//4.獲取One接口的實現類對象PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);//5.調用實現類的方法,接收結果List<Student> list = mapper.selectAll();//6.處理結果for (Student c : list) {System.out.println(c);}//7.釋放資源sqlSession.close();is.close();}總結
以上是生活随笔為你收集整理的Mybatis构建sql语法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 封装this关键字
- 下一篇: 华为鸿蒙山海,华为包圆了整部《山海经》,