and content = #{content}
</if>
<if test="owner != null">
and owner = #{owner}
</if>
</where>
</select></pre>
</div>
where元素的作用是會在寫入where元素的地方輸出一個where,另外一個好處是你不需要考慮where元素里面的條件輸出是什么樣子的,MyBatis會智能的幫你處理,如果所有的條件都不滿足那么MyBatis就會查出所有的記錄,如果輸出后是and 開頭的,MyBatis會把第一個and忽略,當然如果是or開頭的,MyBatis也會把它忽略;此外,在where元素中你不需要考慮空格的問題,MyBatis會智能的幫你加上。像上述例子中,如果title=null, 而content != null,那么輸出的整個語句會是select * from t_blog where content = #{content},而不是select * from t_blog where and content = #{content},因為MyBatis會智能的把首個and 或 or 給忽略。
<select id="dynamicForeachTest" resultType="Blog">
select * from t_blog where id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select></pre>
</div>
上述collection的值為list,對應的Mapper是這樣的
public List<Blog> dynamicForeachTest(List<Integer> ids);
測試代碼:
@Test
public void dynamicForeachTest() {
SqlSession session = Util.getSqlSessionFactory().openSession();
BlogMapper blogMapper = session.getMapper(BlogMapper.class);
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(3);
ids.add(6);
List<Blog> blogs = blogMapper.dynamicForeachTest(ids);
for (Blog blog : blogs)
System.out.println(blog);
session.close();
}
2.單參數array數組的類型:
</div>
<select id="dynamicForeach2Test" resultType="Blog">
select * from t_blog where id in
<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select></pre>
</div>
上述collection為array,對應的Mapper代碼:
public List<Blog> dynamicForeach2Test(int[] ids);
對應的測試代碼:
@Test
public void dynamicForeach2Test() {
SqlSession session = Util.getSqlSessionFactory().openSession();
BlogMapper blogMapper = session.getMapper(BlogMapper.class);
int[] ids = new int[] {1,3,6,9};
List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);
for (Blog blog : blogs)
System.out.println(blog);
session.close();
}
3.自己把參數封裝成Map的類型
<select id="dynamicForeach3Test" resultType="Blog">
select * from t_blog where title like "%"#{title}"%" and id in
<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select></pre>
</div>
上述collection的值為ids,是傳入的參數Map的key,對應的Mapper代碼:
public List<Blog> dynamicForeach3Test(Map<String, Object> params);
對應測試代碼:
@Test
public void dynamicForeach3Test() {
SqlSession session = Util.getSqlSessionFactory().openSession();
BlogMapper blogMapper = session.getMapper(BlogMapper.class);
final List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
ids.add(6);
ids.add(7);
ids.add(9);
Map<String, Object> params = new HashMap<String, Object>();
params.put("ids", ids);
params.put("title", "中國");
List<Blog> blogs = blogMapper.dynamicForeach3Test(params);
for (Blog blog : blogs)
System.out.println(blog);
session.close();
}