今天我们主要讲解
1、mybatis动态sql
2、模糊查询
3、查询返回结果集的处理
4、分页查询
5、特殊字符处理
1、mybatis动态sql
在参数前面加上@Param(“bookIds”)的作用是在Mapper.xml中可以使用,里面放的是别名。
List<Book> selectByIn(@Param("bookIds") List bookIds);
在Mapper接口中定义好方法,然后alt + 回车。选择下图所示。
<select id="selectByIn" resultType="com.zking.model.Book" parameterType="java.util.List">
select * from t_mvc_book where bid in
<foreach collection="bookIds" open="(" close=")" separator="," item="bid">
#{bid}
</foreach>
</select>
resultType 是你返回来的数据类型,
parameterType 是你参数的数据类型,
select中间就是你要执行的sql语句
除了foreach还有if,trim if即是判断,trim则是去空格等动态sql可以生成。
foreach使用规则:
separator 是使用什么隔开。
item 则是代表着集合中的每个元素。
然后进行测试
@Test
public void insert() {
List list = new ArrayList();
list.add(15);
list.add(19);
list.add(26);
list.add(36);
List<Book> books = this.bookService.selectByIn(list);
for (Book b : books) {
System.out.println(b);
}
}
模糊查询
讲解三种模糊查
#{…}
${…}
Concat sql语句
Mapper接口:
List<Book> selectByLike1(@Param("bname") String bname);
List<Book> selectByLike2(@Param("bname") String bname);
List<Book> selectByLike3(@Param("bname") String bname);
sql:
这里可看到我第一个使用的是#{}、第二个使用的是${}、第三个使用的是concat()函数。后面会为大家讲解这三种区别
<select id="selectByLike1" resultType="com.zking.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like #{bname}
</select>
<select id="selectByLike2" resultType="com.zking.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like '${bname}'
</select>
<select id="selectByLike3" resultType="com.zking.model.Book" parameterType="java.lang.String">
select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%&