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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-04-02 我要评论

起因

我们先来看一个报错

报错很简单,参数 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 来命名。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们