版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hlx20080808/article/details/89947069
用注解来简化xml配置的时候,@Param注解的作用是给参数命名,
参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中
@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);
1.传递单个参数,不使用 @Param 注解
public Userinfo find(Userinfo info) throws Exception;
<select id="find" resultType="Userinfo">
select * from userinfo where userName=#{userName}
</select>
这里只有一个参数,java 接口不使用 @Param 注解,同时 mapper 文件也不需要使用 parameterType 这个参数,Mybatis会 根据实体类(entity)的类型自动识别并匹配javaBean(这一部分在 spring配置文件关于数据源那一部分)
2.传递单个参数,使用@Param注解
// 查询某一件商品
Commodity queryOne(@Param("commodity")Commodity commodity);
<select id="queryOne" parameterType="com.hlx.entity.Commodity" resultType="Commodity">
select *
from t_commodity com
where id = #{commodity.id}
</select>
当使用javaBean作为对象的时候,在写 SQL 语句的时候,必须指定参数类parameterType="com.hlx.entity.Commodity",同时在 #{ } 取值的时候不能直接填入 javaBean 的属性,必须这样使用 commodity.id ;否则,会抛出参数类型不匹配异常
如果不是 javaBean,则需要在写 SQL 语句的时候, #{ } 中的属性必须与 @Param中定义的一致, @Param("username") , #{username} ,这样才可以。
3.传递多个参数,使用 @Param 注解
UserInfo users(@Param("account1")String account,@Param("passcode1")String passcode);
<select id="users" resultType="UserInfo">
select *
from t_userinfo info
where account=#{account1} and passcode=#{passcode1}
</select>
这里 @Param 中定义的变量名必须和 mapper 中保持一致才可以
4.传递多个参数,不使用 @Param 注解
从第一种场景中已经可以实现传递多个参数了,即把多个参数封装到一个 javaBean 中就可以实现了,但是如果是两个或者多个 javaBean 的时候,可以通过使用@Param注解的方式来实现,但是需要把每个 javaBean 中的属性全部拆分出来,这样就增加了巨大的代码量,因此不推荐这么做!
主要是为了说明,Mybatis无论是传单个参数,还是传递多个参数,没有必要使用@Param注解!!!!
那么有没有可以不使用@Param注解,同样也可以传递多个参数(尤其是多个 javaBean
),如下:
// 搜索用户,对结果进行分页
List searchUser(Map<String,Object>);
UserInfo userInfo = new UserInfo();
Pagination page = new Pagination();
Map<String,Object> map = new HashMap<>;
map.put("userInfo",userInfo);
pam.put("page",page);
userService.searchUser(map);
<select id="searchUser" parameterType="java.util.Map" resultType="UserInfo">
select *
from t_userinfo user
where 1 =1
<if test="user.uname != null and ''!= user.uname ">
and user.uname like '%${userInfo.uname}$%'
</if>
<if test="page.order != null and page.order == 10" >
order by user.id asc
</if>
limit ${page.pagenum * page.limitnum}, #{page.limitnum}
</select>