用註解來簡化xml配置的時候,@Param註解的作用是給參數命名,參數命名後就能根據名字得到參數值,正確的將參數傳入sql語句中
我們先來看Mapper接口中的@Select方法
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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("參數名"),表示給參數命名,名稱就是括號中的內容
public Student select(@Param("aaaa") String name,@Param("bbbb")int class_id);
給入參 String name 命名爲aaaa,然後sql語句....where s_name= #{aaaa} 中就可以根據aaaa得到參數值了
就是你這裏傳的參數必須要和mapper.xml裏的#{參數}一致!
userMapper.java
public String getUsernameById(@Param("YG_ID") int id);
userMapper.XML
<select id="getUsernameById" resultType="String"> select XXXX from XXXX where YG_ID = #{YG_ID} </select>
1,使用@Param註解
當以下面的方式進行寫SQL語句時:
@Select("select column from table where userid = #{userid} ")
public int selectColumn(int userid);
當你使用了使用@Param註解來聲明參數時,如果使用 #{} 或 ${} 的方式都可以。
@Select("select column from table where userid = ${userid} ")
public int selectColumn(@Param("userid") int userid);
當你不使用@Param註解來聲明參數時,必須使用使用 #{}方式。如果使用 ${} 的方式,會報錯。
@Select("select column from table where userid = ${userid} ")
public int selectColumn(@Param("userid") int userid);
2,不使用@Param註解
不使用@Param註解時,參數只能有一個,如果有多個參數(int,String等)的話,必須用map取值,用索引取值,麻煩而且不清晰。
注意,使用了@pram註解的話在mapper.xml不加parameterType,因爲在接口就聲明瞭類型,加上@pram後自動識別
在SQL語句裏可以引用JavaBean的屬性,而且只能引用JavaBean的屬性。
// 這裏id是user的屬性
@Select("SELECT * from Table where id = ${id}")
Enchashment selectUserById(User user);