为什么要使用mybatis的@param

起因

我们先来看一个报错
在这里插入图片描述

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

在这里插入图片描述

题外话的小字:这几天在准备软考,我发现大学里还真的没考什么证书来,最近在看看教师资格证的考试,想试试当老师,然后刚刚又在查看公务员考试,在想去事业单位或者去当公务员,人生的岔路口真的太多了,真担心自己一不小心就走丢了。

猜你喜欢

转载自blog.csdn.net/Caeser110/article/details/102510782