mybatis學(xué)習(xí)筆記之mybatis注解配置詳解

Java API

創(chuàng)新互聯(lián)建站-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比路橋網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式路橋網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋路橋地區(qū)。費用合理售后完善,十余年實體公司更值得信賴。

既然你已經(jīng)知道如何配置 MyBatis 和創(chuàng)建映射文件,你就已經(jīng)準備好來提升技能了。 MyBatis 的 Java API 就是你收獲你所做的努力的地方。正如你即將看到的,和 JDBC 相比, MyBatis 很大程度簡化了你的代碼而且保持簡潔,很容易理解和維護。MyBatis 3 已經(jīng)引入 了很多重要的改進來使得 SQL 映射更加優(yōu)秀。

MyBatis 3構(gòu)建在基于全面且強大的Java配置API上。該配置API是基于XML的MyBatis配置的基礎(chǔ),也是新的基于注解配置的基礎(chǔ)。

注解提供了一種簡單的方式來實現(xiàn)簡單映射語句,而不會引入大量的開銷。

Mybatis常用注解對應(yīng)的目標和標簽如表所示:

注解目標對應(yīng)的XML標簽
@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)建動態(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):一些查詢的選項開關(guān)

@Param("id"):全局限定別名,定義查詢參數(shù)在sql語句中的位置不再是順序下標0,1,2,3......的形式,而是對應(yīng)名稱,該名稱在此處定義。 

@Results是以@Result為元素的數(shù)組,@Result表示單條屬性——字段的映射關(guān)系,id = true表示該id字段是主鍵,查詢時mybatis會給予必要的優(yōu)化。數(shù)組中所有的@Result組成了單個記錄的映射關(guān)系,而@Results則是單個記錄的集合。另外,還有一個非常重要的注解@ResultMap,其與@Results類似

@Select("查詢語句")、@Insert("增加語句")、@Update("更新語句")和@Delete("刪除語句")表示對數(shù)據(jù)進行查詢、添加、更新和刪除的操作。

接下來,咱們來看一下注解的使用。

(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);

如果多個查詢返回的結(jié)果集結(jié)構(gòu)都一樣,可以使用@ResultMap定義返回結(jié)構(gòu),使用該注解,你將不得不在你的映射文件中配置你的resultMap,而@ResultMap(value = "名")即為映射文件中的resultMap ID,如此一來,你需要在<mapper>中注冊你的配置文件,在接口中使用@ResultMap來引用配置文件中的resultMap ID如下:

示例3

SelfMapper.xml

 //每行記錄是一個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   查詢一個對象

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配置和核心配置文件進行關(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   傳遞多個參數(shù),查詢多個對象

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配置和核心配置文件進行關(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配置和核心配置文件進行關(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進行關(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配置和核心配置文件進行關(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", "計算機系"); 
   //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í)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

網(wǎng)站名稱:mybatis學(xué)習(xí)筆記之mybatis注解配置詳解
分享鏈接:http://muchs.cn/article48/jpishp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站品牌網(wǎng)站設(shè)計、建站公司、品牌網(wǎng)站制作、網(wǎng)站排名、網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司