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


我是在实现一个 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 来命名。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM