现在的位置: 首页 > 编程语言 > 正文

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

2020年02月13日 编程语言 ⁄ 共 1342字 ⁄ 字号 评论关闭

起因

我们先来看一个报错

报错很简单,参数 start 没找到。

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

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 层

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

<select id="getTypeListByRange" resultType="com.caeser.upmovie.entity.Type"> SELECT ID, NAME, CREATE_TIME, UPDATE_TIME FROM upm_type LIMIT #{start},#{end}; </select>

单元测试

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

以上就上有关浅谈为什么要使用mybatis的@param的相关介绍,要了解更多mybatis,@param内容请登录学步园。

抱歉!评论已关闭.