关于为什么要用Mybatis中的@Param

    个人做的一些总结。首先引出问题,为什么要用@Param?

    Java没有保存形参的记录,例如queryAll(int offet,int limit) 就相当于queryAll(arg0,arg1),参数只能根据索引0

、1来进行区分。mybatis就提供了@Param这个注解来完成命名传入参数,这样mybatis才能通过参数名字将数

据传入#{}中。

    为说明问题举以下示例:

1.如果mapper接口里参数是两个普通参数;如下图

public List<student> selectuser(int pn ,String i);

  1. <select id="selectuser" resultType="com.user.entity.student">
  2. SELECT * FROM student
  3. where sname like concat(concat("%",#{1}),"%")
  4. LIMIT #{0} ,5
  5. </select>

    那么xml里只能用#{0},#{1}的方式,但这样的表达方法,无法表达出参数的意义,不利于后期的维护。 可以用@Param的注解来修饰参数。xml里看起来也比较方便,否则一堆0,1,2,3的真是难懂。

public List<student> selectuser(@Param(value = "page")int pn ,@Param(value = "str")String i);

  1. <select id="selectuser" resultType="com.user.entity.student">
  2. SELECT * FROM student
  3. where sname like concat(concat("%",#{str}),"%")
  4. LIMIT #{page} ,5
  5. </select>

2,如果传入的参数是基本类型参数和实体类对象。

public List<student> selectuser(@Param(value = "page")int pn ,@Param(value = "st")student student);

  1. <select id="selectuser" resultType="com.user.entity.student">
  2. SELECT * FROM student
  3. where sname like concat(concat("%",#{st.sname}),"%")
  4. LIMIT #{page} ,5
  5. </select>

3.如果传入的参数只有一个,基本上不用@Param这个注解了,因为只有一个参数MyBatis就不需要区分了,不像多个参数要区分谁是谁,所以正常用。

public List<student> selectuser(int pn);

  1. <select id="selectuser" resultType="com.user.entity.student">
  2. SELECT * FROM student
  3. <!--where sname like concat(concat("%",#{st.sname}),"%")-->
  4. LIMIT #{page} ,5

猜你喜欢

转载自blog.csdn.net/qq_42365082/article/details/80982539
今日推荐