用注解來簡化xml配置的時候,@Param注解的作用是給參數命名,參數命名后就能根據名字得到參數值,正確的將參數傳入sql語句中
我們先來看Mapper接口中的@Select方法
1
2
3
4
5
6
7
|
package Mapper; public interface Mapper { @Select ( "select s_id id,s_name name,class_id classid from student where s_name= #{aaaa} and class_id = #{bbbb}" ) public Student select( @Param ( "aaaa" ) String name, @Param ( "bbbb" ) int class_id); @Delete ...... @Insert ...... } |
這里解釋一下
1.@Select(....)注解的作用就是告訴mybatis框架,執行括號內的sql語句
2.s_id id,s_name name,class_id classid
格式是 字段名+屬性名,例如s_id是數據庫中的字段名,id是類中的屬性名
這段代碼的作用就是實現數據庫字段名和實體類屬性的一一映射,不然數據庫不知道如何匹配
3.where s_name= #{aaaa} and class_id = #{bbbb}
表示sql語句要接受2個參數,一個參數名是aaaa,一個參數名是bbbb,如果要正確的傳入參數,那么就要給參數命名,因為不用xml配置文件,那么我們就要用別的方式來給參數命名,這個方式就是@Param注解
4.在方法參數的前面寫上@Param("參數名"),表示給參數命名,名稱就是括號中的內容
1
|
public Student select( @Param ( "aaaa" ) String name, @Param ( "bbbb" ) int class_id); |
給入參 String name 命名為aaaa,然后sql語句....where s_name= #{aaaa} 中就可以根據aaaa得到參數值了
PS:下面看下spring中@param和mybatis中@param使用區別
1.spring中@param
1
2
3
4
5
6
|
/** * 查詢指定用戶和企業關聯有沒有配置角色 * @param businessId memberId * @return */ int selectRoleCount( @Param ( "businessId" ) Integer businessId, @Param ( "memberId" ) Long memberId); |
2.mybatis中的param
1
2
3
4
5
6
|
/** * 查詢指定用戶和企業關聯有沒有配置角色 * @param businessId memberId * @return */ int selectRoleCount( @Param ( "businessId" ) Integer businessId, @Param ( "memberId" ) Long memberId); |
從表面上看,兩種并沒有區別,但是在xml文件中使用的時候是有區別的,Spring中的@param在xml需要如下這樣引用變量
1
2
3
4
5
6
7
8
|
<select id= "selectRoleCount" resultType= "java.lang.Integer" > select count(tbm.id) from t_business_member_relation tbm where tbm.business_id = #{ 0 ,jdbcType=INTEGER} and tbm.member_id = #{ 1 ,jdbcType=INTEGER} and tbm.role_business_id is not null </select> |
是根據參數的順序來取值的,并且從0開始。而在mybatis @param在xml中則是如下這樣引用變量的
1
2
3
4
5
6
7
8
|
<select id= "selectRoleCount" resultType= "java.lang.Integer" > select count(tbm.id) from t_business_member_relation tbm where tbm.business_id = #{businessId,jdbcType=INTEGER} and tbm.member_id = #{memberId,jdbcType=INTEGER} and tbm.role_business_id is not null </select> |
是通過參數名來引用的
注:如果Mapper.java文件中引用的是Spring的
1
|
org.springframework.data.repository.query.Param; |
但是Mapper.xml中使用的是mybatis 的用法,那么就會如下的錯誤
1
|
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'businessId' not found. Available parameters are [ 1 , 0 , param1, param2] |
截圖如下
所以在使用的時候一定要注意@param引用和使用的一致性
總結
以上所述是小編給大家介紹的Mybatis中@Param的用法和作用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/li12412414/article/details/78127256