前言
上篇文章简单分享了MyBatis的入门,这次就来分享Mybatis的动态SQL和分页。
一、MyBatis的if、foreach标签
我们自动生成的增删改查方法,跟之前自定义MVC还是不一样的。同样的增加方法在自定义MVC中是这样的。
Insert into t_mvc_book(id,name,price) values(?,?,?)
我们要传三个参数。假设id不为自动增长,name = zs, price = 11;那么id就为null。
而mybatis自动生成的就有所不同。
1、if标签
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="bid != null" >
bid,
</if>
<if test="bname != null" >
bname,
</if>
<if test="price != null" >
price,
</if>
</trim>
在MyBatis生成的方法中,用到了if标签,判断该字段是否为null,如果该字段为空,就不会拼接该字段。
例如:id为空,其他不为空。SQL语句是
Insert into t_mvc_book(name,price) values(?,?)
2、foreach标签
我们查询时,会有查询数据库中在某个集合中的内容。
例如 selec from t_mvc_book where bid in(31,32,33,34)之类的。
如果用for循环或者foreach将数组转变为字符串
或许会用以下方式
public void test3(){ int[] ints = {1,2,3,4,5,6}; // 将数组转成字符串 StringBuffer sb = new StringBuffer(); for (int i:ints){ sb.append(i); sb.append(","); } System.out.println(sb); }
明显多了一个逗号。或许在分割一下就OK了
而mybatis中的foreach标签就不一样啦。
// 如果参数 为非实体类 记得 加注解
List<Book> selectByIn(@Param("bookIds") List bookIds);
<select id="selectByIn" resultMap="BaseResultMap" parameterType="java.util.List" >
select
<include refid="Base_Column_List" />
from t_mvc_book
where bid in
<foreach collection="bookIds" open="(" close=")" separator="," item="bid">
#{bid}
</foreach>
</select>
@Test
public void selectByIn() {
bookBiz.selectByIn(Arrays.asList(new Integer[]{31,32,33,34})).forEach(System.out: