码迷,mamicode.com
首页 > 其他好文 > 详细

浅谈为什么要使用mybatis的@param

时间:2020-02-06 21:37:31      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:多个参数   val   target   width   cin   htm   ota   oid   border   

我是在实现一个 API 接口时发现了一个问题,当我不使用 @Param 标签时,mybatis 是不认识哪个参数叫什么名字的,尽管我定义了 (long start,long end) 它仍然不认识。在这个接口上,我希望根据前端传来的参数,查找指定范围的数据,例如:我想搜索第二页的数据,假设一页20个,那么搜索的范围就是21-40,于是就会调用接口中的 getTypeListByRange 来查找对应 mapper 的 SQL 语句。

1
2
3
4
5
public interface TypeDao {
 Type getTypeByid(long id);
 List<Type> getTypeListAll();
 List<Type> getTypeListByRange(long start,long end);
}

解释 @Param

org.apache.ibatis.annotations.Param 当映射器方法需要多个参数时,这个注解可以被用于:给映射器方法中的每个参数来取一个名字。否则,多参数将会以它们的顺序位置和SQL语句中的表达式进行映射,这是默认的。
语法要求:若使用@Param(“id”),则SQL中参数应该被命名为:#{id}。

使用

Dao 层

1
2
3
4
5
6
7
8
9
import org.apache.ibatis.annotations.Param;
 
import com.caeser.upmovie.entity.Type;
 
public interface TypeDao {
 Type getTypeByid(long id);
 List<Type> getTypeListAll();
 List<Type> getTypeListByRange(@Param("start")long start,@Param("end")long end);
}

Mapper

1
2
3
4
5
6
7
8
9
10
11
<select id="getTypeListByRange"  resultType="com.caeser.upmovie.entity.Type">
 SELECT
 ID,
 NAME,
 CREATE_TIME,
 UPDATE_TIME
 FROM
 upm_type
 LIMIT
  #{start},#{end};
 </select>

单元测试

1
2
3
4
5
6
7
8
9
10
11
12
public class TypeTest extends BaseTest{
 @Autowired
 private TypeDao typeDao;
  
 @Test
 public void testDao(){
 List<Type> typeList1=typeDao.getTypeListByRange(1, 4);
 for(int i=0;i<typeList1.size();i++){
  System.out.println(typeList1.get(i).getName());
 }
 }
}

结果

技术图片

总结

当 Dao 层传递参数为多个参数时,为了规范,必须使用 @Param 给参数命名。这里需要注意,使用的是 mybatis 的 param 来命名。

浅谈为什么要使用mybatis的@param

标签:多个参数   val   target   width   cin   htm   ota   oid   border   

原文地址:https://www.cnblogs.com/360minitao/p/12270937.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!