mybatis學(xué)習(xí)筆記之mybatis注解配置詳解
Java API
既然你已經(jīng)知道如何配置 MyBatis 和創(chuàng)建映射文件,你就已經(jīng)準(zhǔn)備好來提升技能了。 MyBatis 的 Java API 就是你收獲你所做的努力的地方。正如你即將看到的,和 JDBC 相比, MyBatis 很大程度簡化了你的代碼而且保持簡潔,很容易理解和維護(hù)。MyBatis 3 已經(jīng)引入 了很多重要的改進(jìn)來使得 SQL 映射更加優(yōu)秀。
MyBatis 3構(gòu)建在基于全面且強(qiáng)大的Java配置API上。該配置API是基于XML的MyBatis配置的基礎(chǔ),也是新的基于注解配置的基礎(chǔ)。
注解提供了一種簡單的方式來實(shí)現(xiàn)簡單映射語句,而不會(huì)引入大量的開銷。
Mybatis常用注解對應(yīng)的目標(biāo)和標(biāo)簽如表所示:
注解 | 目標(biāo) | 對應(yīng)的XML標(biāo)簽 |
@CacheNamespace | 類 | <cache> |
@CacheNamespaceRef | 類 | <cacheRef> |
@Results | 方法 | <resultMap> |
@Result | 方法 |
<result> <id> |
@One | 方法 | <association> |
@Many | 方法 | <collection> |
@Insert @Update @Delete |
方法 |
<insert> <update> <delete> |
@InsertProvider @UpdateProvider @DeleteProvider @SelectProvider |
方法 |
<insert> <update> <delete> <select> 允許創(chuàng)建動(dòng)態(tài)SQL |
@Param | 參數(shù) | N/A |
@Options | 方法 | 映射語句的屬性 |
@select | 方法 | <select> |
Mybatis常用注解的含義:
@CacheNamespace(size = 512):定義在該命名空間內(nèi)允許使用內(nèi)置緩存
@Options(useCache = true, flushCache = false, timeout = 10000):一些查詢的選項(xiàng)開關(guān)
@Param("id"):全局限定別名,定義查詢參數(shù)在sql語句中的位置不再是順序下標(biāo)0,1,2,3......的形式,而是對應(yīng)名稱,該名稱在此處定義。
@Results是以@Result為元素的數(shù)組,@Result表示單條屬性——字段的映射關(guān)系,id = true表示該id字段是主鍵,查詢時(shí)mybatis會(huì)給予必要的優(yōu)化。數(shù)組中所有的@Result組成了單個(gè)記錄的映射關(guān)系,而@Results則是單個(gè)記錄的集合。另外,還有一個(gè)非常重要的注解@ResultMap,其與@Results類似
@Select("查詢語句")、@Insert("增加語句")、@Update("更新語句")和@Delete("刪除語句")表示對數(shù)據(jù)進(jìn)行查詢、添加、更新和刪除的操作。
接下來,咱們來看一下注解的使用。
(1) 常規(guī)注解使用(不需要自定義map的操作):
示例1
//添加作者 @Insert("Insertinto Author(username,password,email,address,phone) " + "values(#{username},#{password},#{email},#{address},#{phone})") @Options(useGeneratedKeys=true,keyProperty="authId",flushCache= false, timeout = 10000) public voidaddAuthor(Author author); //刪除作者 @Delete("deletefrom author where id = #{id}") @Options(flushCache= false, timeout = 10000) public voiddeleteAuthor(@Param("id") int id);
提示: 調(diào)用方法前需要注冊映射器:
sessionFactory.getConfiguration().addMapper(TestInteger.class);
或者在mapper.xml中配置<mapper class="映射器接口路徑"></mapper>
注冊之后再獲取mapper接口正常調(diào)用
(2)有需要自定義map的情況可以使用Results注解:
示例2
//查詢所有作者信息 @Select("select * from author") @Options(flushCache = false, timeout = 10000,useCache=true) @Results( value = { @Result(id=true,column="id",property="id"), @Result(property="username",column="username"), @Result(property="password",column="password"), @Result(property="email",column="email"), @Result(property="address",column="address"), @Result(property="phone",column="phone") } ) public List<Author> findAuthors(); //查詢某作者信息 @Select("select * from author where id =#{id}") @Options(flushCache = false, timeout =10000,useCache=true) @Results( value = {@Result(id=true,column="id",property="id"), @Result(property="username",column="username"), @Result(property="password",column="password"), @Result(property="email",column="email"), @Result(property="address",column="address"), @Result(property="phone",column="phone") } ) public Author findAuthorById(@Param("id") intid);
如果多個(gè)查詢返回的結(jié)果集結(jié)構(gòu)都一樣,可以使用@ResultMap定義返回結(jié)構(gòu),使用該注解,你將不得不在你的映射文件中配置你的resultMap,而@ResultMap(value = "名")即為映射文件中的resultMap ID,如此一來,你需要在<mapper>中注冊你的配置文件,在接口中使用@ResultMap來引用配置文件中的resultMap ID如下:
示例3
SelfMapper.xml
//每行記錄是一個(gè)hashmap <resultMaptype="java.util.HashMap" id="selfMap"> <resultproperty="n" column="city_name" /> ............... </resultMap>
SelfMapper.java:
@Select("select a.id,b.name,c.state from...........") @ResultMap(value="selfMap") public List<HashMap> sel();//注意,返回的是List集合
完整案例
接口代碼
package com.obtk.dao; import java.util.HashMap; import java.util.List; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import com.obtk.entitys.StudentEntity; public interface IStudentDao { @Insert("insert into Student(stuName,gender,age,address,deptIdd)"+ "values(#{stuName},#{gender},#{age},#{address},#{deptIdd})") @Options(useGeneratedKeys=true,keyProperty="stuId") int saveOne(StudentEntity stu); @Select("select * from Student where stuId=#{stuId}") @Results( //只要配置和列名不一致的屬性 value={ @Result(column="gender",property="sex") } ) StudentEntity queryById(Integer stuId); @Select("select * from Student where gender=#{qqq} and address=#{area}") @Results( //只要配置和列名不一致的屬性 value={ @Result(column="gender",property="sex") } ) List<StudentEntity> queryByMany(HashMap theMap); //萬能關(guān)聯(lián)注解配置 @Select("select * from student s inner join department d" +" on s.deptIdd=d.deptId" +" where s.gender=#{sex}" +" and d.departName=#{deptName}") List<HashMap> queryByQnn(HashMap theMap); }
案例1 查詢一個(gè)對象
package com.obtk.test; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.obtk.dao.IStudentDao; import com.obtk.entitys.StudentEntity; import com.obtk.utils.MybatisUtil; public class AnnoSelectOne { public static void main(String[] args) { SqlSession session=null; SqlSessionFactory factory=null; try { session=MybatisUtil.getSession(); factory=MybatisUtil.getFactory(); //把接口里面的sql配置和核心配置文件進(jìn)行關(guān)聯(lián) factory.getConfiguration().addMapper(IStudentDao.class); IStudentDao stuDao=session.getMapper(IStudentDao.class); StudentEntity stu=stuDao.queryById(129); System.out.println(stu.getStuName()+","+stu.getSex() +","+stu.getAddress()+","+stu.getStuId()); } catch (Exception e) { e.printStackTrace(); }finally{ MybatisUtil.closeSession(); } } }
案例2 傳遞多個(gè)參數(shù),查詢多個(gè)對象
package com.obtk.test; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.obtk.dao.IStudentDao; import com.obtk.entitys.StudentEntity; import com.obtk.utils.MybatisUtil; public class AnnoSelectMany { public static void main(String[] args) { SqlSession session=null; SqlSessionFactory factory=null; try { session=MybatisUtil.getSession(); factory=MybatisUtil.getFactory(); //把接口里面的sql配置和核心配置文件進(jìn)行關(guān)聯(lián) factory.getConfiguration().addMapper(IStudentDao.class); IStudentDao stuDao=session.getMapper(IStudentDao.class); HashMap paramMap=new HashMap(); paramMap.put("qqq", "男"); paramMap.put("area", "學(xué)生宿舍"); List<StudentEntity> stuList=stuDao.queryByMany(paramMap); for(StudentEntity stu :stuList){ System.out.println(stu.getStuName()+","+stu.getSex() +","+stu.getAddress()+","+stu.getStuId()); } } catch (Exception e) { e.printStackTrace(); }finally{ MybatisUtil.closeSession(); } } }
案例3 添加對象
package com.obtk.test; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.obtk.dao.IStudentDao; import com.obtk.entitys.StudentEntity; import com.obtk.utils.MybatisUtil; public class AnnoSaveTest { public static void main(String[] args) { SqlSession session=null; SqlSessionFactory factory=null; try { session=MybatisUtil.getSession(); factory=MybatisUtil.getFactory(); //把接口里面的sql配置和核心配置文件進(jìn)行關(guān)聯(lián) factory.getConfiguration().addMapper(IStudentDao.class); IStudentDao stuDao=session.getMapper(IStudentDao.class); StudentEntity stu=new StudentEntity("testC#", "男", 21, "冥王星"); stu.setDeptIdd(10); int result=stuDao.saveOne(stu); session.commit(); System.out.println("保存成功:"+stu.getStuId()); } catch (Exception e) { e.printStackTrace(); }finally{ MybatisUtil.closeSession(); } } }
案例4 利用hashmap進(jìn)行關(guān)聯(lián)查詢
package com.obtk.test; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.obtk.dao.IStudentDao; import com.obtk.entitys.StudentEntity; import com.obtk.utils.MybatisUtil; public class AnnoJoinQnn { public static void main(String[] args) { SqlSession session=null; SqlSessionFactory factory=null; try { //4.得到session session=MybatisUtil.getSession(); factory=MybatisUtil.getFactory(); //把接口里面的sql配置和核心配置文件進(jìn)行關(guān)聯(lián) factory.getConfiguration().addMapper(IStudentDao.class); IStudentDao stuDao=session.getMapper(IStudentDao.class); HashMap paramMap=new HashMap(); paramMap.put("sex", "男"); paramMap.put("deptName", "計(jì)算機(jī)系"); //5.執(zhí)行語句 List<HashMap> stuList=stuDao.queryByQnn(paramMap); for(HashMap theObj : stuList){ System.out.println(theObj.get("stuId")+","+theObj.get("gender") +","+theObj.get("stuName")+","+theObj.get("departName")); } } catch (Exception e) { e.printStackTrace(); }finally{ MybatisUtil.closeSession(); } } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
IntelliJ IDEA中如何構(gòu)建Spring Boot的項(xiàng)目
這篇文章主要介紹了IntelliJ IDEA中如何構(gòu)建Spring Boot的項(xiàng)目問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07Netty分布式pipeline管道傳播事件的邏輯總結(jié)分析
這篇文章主要為大家介紹了Netty分布式pipeline管道傳播事件總結(jié)分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-03-03mybatis-plus使用generator實(shí)現(xiàn)逆向工程
mybatis-plus-generator在3.5.0以及以后的版本使用新的方式逆向生成代碼,本文主要介紹了mybatis-plus使用generator實(shí)現(xiàn)逆向工程,具有一定的參考價(jià)值,感興趣的可以了解一下2022-05-05springboot加載命令行參數(shù)ApplicationArguments的實(shí)現(xiàn)
本文主要介紹了springboot加載命令行參數(shù)ApplicationArguments的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-0414個(gè)編寫Spring MVC控制器的實(shí)用小技巧(吐血整理)
這篇文章主要介紹了14個(gè)編寫Spring MVC控制器的實(shí)用小技巧(吐血整理),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11手把手教你使用IDEA創(chuàng)建多模塊(maven)項(xiàng)目
這篇文章主要給大家介紹了關(guān)于如何使用IDEA創(chuàng)建多模塊(maven)項(xiàng)目的相關(guān)資料,文中通過圖文以及實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07