Mybatis传入多个参数
顺序传参
适合传入参数较少时(多的话可以用Map)
// mapper接口方法
List<News> selectByIdAndState(int newsId,int delState);
//sql语句
<select id="selectByIdAndState3" resultType="com.springboot.book.entity.News">
select * from news where news_id > #{param1} and delState = #{param2}
</select>
使用@Param注解
和顺序传参一样,向方法中传入多个参数,不同的是添加@Param注解,为参数命名,然后再xml中获取
// mapper接口方法
List<News> selectByIdAndState(@Param("id") int newsId, @Param("state") int delState);
//sql语句
<select id="selectByIdAndState3" resultType="com.springboot.book.entity.News">
select * from news where news_id > #{id} and delState = #{state}
</select>
Map传参
使用map以键值对的形式传参,然后再xml中根据key值获取参数值
//mapper接口方法
List<News> selectByIdAndState(Map<String,Object> map);
//sql语句
<select id="selectByIdAndState" resultType="com.springboot.book.entity.News">
select * from news where news_id > #{newsId} and delState = #{delState}
</select>
//测试方法
@Test
void test(){
Map<String,Object> map = new HashMap<>();
map.put("newsId",1);
map.put("delState",0);
List<News> list = newsDao.selectByIdAndState(map); list.forEach(news-> System.out.println(news));
}
List传参/数组传参
一般用于批量删除,传入多个id
//mapper接口方法
int deleteByList(List<Integer> list);int deleteByArray(int[] arr);
//sql语句
<delete id="deleteByList">
update news set delState = 1 where news_id in
<foreach collection="list" open="(" separator="," close=")" item="id">
#{id}
</foreach>
</delete>
<delete id="deleteByArray">
update news set delState = 1 where news_id in
<foreach collection="array" open="(" separator="," close=")" item="id">
#{id}
</foreach>
</delete>
//测试方法,这里删除为改变数据库的状态,不是真正意义上的删除,所以用的update语句
/**
* ==> Preparing: update news set delState = 1 where news_id in ( ? , ? , ? )
* * ==> Parameters: 1(Integer), 5(Integer), 6(Integer)
* * <== Updates: 3
* */
@Test
void testDelete01(){
int result = newsDao.deleteByArray(new int[]{1, 5, 6});
System.out.println("影响的数据条数:"+result);
}
/**
* ==> Preparing: update news set delState = 1 where news_id in ( ? , ? , ? )
* ==> Parameters: 7(Integer), 8(Integer), 9(Integer)
* <== Updates: 3
*/
@Test
void testDelete02(){
int result = newsDao.deleteByList(Arrays.asList(new Integer[]{7, 8, 9})); System.out.println("影响的数据条数:"+result);
}
对象传参
将数据用一个实体对象封装传递,解析xml中的sql语句时会调用getXxx()方法获取值
//mapper接口方法
List<News> selectByIdAndState(News news);
//sql语句
<select id="selectByIdAndState2" resultType="com.springboot.book.entity.News">
select * from news where news_id > #{newsId} and delState = #{delState}
</select>
//测试方法
/**
* ==> Preparing: select * from news where news_id > ? and delState = ?
* ==> Parameters: 6(Integer), 0(Integer)
*/
@Testvoid
testSelect02(){
List<News> list = newsDao.selectByIdAndState(new News(6,0));
list.forEach(news-> System.out.println(news));
}