我是在實現一個 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 來命名。