可以方便的在 sql 語句中實現某些邏輯. 總體說來mybatis 動態SQL 語句主要有以下幾類:
1. if 語句 (簡單的條件判斷)
2. where (主要是用來簡化sql語句中where條件判斷的,能智能的處理 and or ,不必擔心多餘導致語法錯誤)
3. choose (when,otherwize) ,與 jstl 中的choose 很類似.滿足一個條件後其他分支就不再執行
4. set (主要用於update語句),下面代碼中沒有示例但是用法差不多也很簡單
5. trim (在自己包含的內容前加上某些前綴或者後綴) 與java中的trim要區分開 java中是去除字符兩邊的空格與製表符
6. foreach (在實現in 語句查詢時特別有用)
新建博客表:
create table t_blog( id number, title varchar(100), content varchar(500), owner varchar(50) )
insert into t_blog values(1,'標題1','內容1','張三'); insert into t_blog values(2,'標題2','內容2','張三'); insert into t_blog values(3,'標題3','內容3','張三'); insert into t_blog values(4,'標題4','內容4','張三');
|
以下是項目中主要的四個源碼文件
Blog.java
package com.lq.model;
public class Blog {
private Integer id;
private String title;
private String content;
private String owner;
public Blog() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 設置別名 -->
<typeAliases>
<typeAlias type="com.lq.model.Blog" alias="blog"/>
</typeAliases>
<!-- 數據源配置 開發環境下設置爲development 可以打印更多的日誌信息 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc自帶的事務管理器,進行簡單的事務開啓和提交 -->
<transactionManager type="JDBC" />
<!-- 使用jdbc自帶的數據庫連接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test1" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!-- 配置mapper映射文件 -->
<mappers>
<mapper resource="com/lq/model/BlogMapper.xml"/>
</mappers>
</configuration>
BlogMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lq.model.BlogMapper">
<!-- where if 語句使用 -->
<select id="queryBlog_if" parameterType="blog" resultType="blog">
select * from t_blog
<where>
<!-- 以下使用模糊查詢的兩種方式,#表示使用佔位符傳參;
$不使用佔位符,直接將參數解析後拼接到SQL中,會引起SQL注入 -->
<if test="title!=null">
and title like '%'||#{title}||'%'
</if>
<if test="content!=null">
and content like '%${content}%'
</if>
<if test="owner!=null">
and owner like '%'||#{owner}||'%'
</if>
</where>
</select>
<!-- choose 語句使用 -->
<select id="queryBlog_choose" parameterType="blog" resultType="blog">
select * from t_blog
<where>
<choose>
<when test="title!=null">and title like '%'||#{title}||'%'</when>
<when test="content!=null">and content like '%${content}%'</when>
<otherwise>and owner = "張三" </otherwise>
</choose>
</where>
</select>
<!-- trim 語句使用 -->
<select id="queryBlog_trim" parameterType="blog" resultType="blog">
select * from t_blog
<trim prefix="where" prefixOverrides="and|or">
<if test="title!=null">
and title like '%'||#{title}||'%'
</if>
<if test="content!=null">
and content like '%${content}%'
</if>
<if test="owner!=null">
and owner like '%'||#{owner}||'%'
</if>
</trim>
</select>
<!-- foreach遍歷list 語句使用 -->
<select id="query_foreach_list" parameterType="list" resultType="blog">
select * from t_blog where 1=1
<if test="list!=null">
and id in
<foreach collection="list" item="id" open="(" close=")" separator=",">#{id}</foreach>
</if>
</select>
<!-- foreach遍歷數組 語句使用 -->
<select id="query_foreach_array" parameterType="int" resultType="blog">
select * from t_blog where 1=1
<if test="array!=null">
and id in
<foreach collection="array" item="id" open="(" close=")" separator=",">#{id}</foreach>
</if>
</select>
<!-- foreach遍歷map 語句使用 -->
<!--
Map map = new HashMap();
map.put("owner", "張三");
map.put("array",array);
當傳遞map時 ,在sql中使用的都是map的key
-->
<select id="query_foreach_map" parameterType="map" resultType="blog">
select * from t_blog where 1=1
<if test="array!=null">
and id in
<foreach collection="array" item="id" open="(" close=")" separator=",">#{id}</foreach>
</if>
<if test="owner!=null">
and owner=#{owner}
</if>
</select>
</mapper>
BlogTest.java 每個test測試方法對應上面一個Select
package com.lq.test;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.lq.model.Blog;
public class BlogTest {
SqlSession session =null;
@Before
public void before(){
//加載核心配置文件
Reader reader;
try {
reader = Resources.getResourceAsReader("SqlMapConfig.xml");
//創建session工廠
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//打開一個和數據庫的會話
session = sessionFactory.openSession();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@After
public void after(){
//提交事務
session.commit();
//關閉連接
session.close();
}
@Test
public void testQuery_if() throws IOException{
Blog blog=new Blog();
blog.setTitle("標題");
blog.setContent("內容");
List<Blog> list=session.selectList("com.lq.model.BlogMapper.queryBlog_if", blog);
for (Blog blog2 : list) {
System.out.println(blog2.getId()+"-----"+blog2.getTitle()+"-----"+
blog2.getContent()+"-----"+blog2.getOwner());
}
}
@Test
public void testQuery_choose() throws IOException{
Blog blog=new Blog();
List<Blog> list=session.selectList("com.lq.model.BlogMapper.queryBlog_choose", blog);
for (Blog blog2 : list) {
System.out.println(blog2.getId()+"-----"+blog2.getTitle()+"-----"+
blog2.getContent()+"-----"+blog2.getOwner());
}
}
@Test
public void testQuery_trim() throws IOException{
Blog blog=new Blog();
blog.setTitle("標題");
blog.setContent("內容");
List<Blog> list=session.selectList("com.lq.model.BlogMapper.queryBlog_trim", blog);
for (Blog blog2 : list) {
System.out.println(blog2.getId()+"-----"+blog2.getTitle()+"-----"+
blog2.getContent()+"-----"+blog2.getOwner());
}
}
@Test
public void queryForeachList() throws IOException{
List list=new ArrayList();
list.add(1);
list.add(2);
List<Blog> blogs=session.selectList("com.lq.model.BlogMapper.query_foreach_list", list);
for (Blog blog2 : blogs) {
System.out.println(blog2.getId()+"-----"+blog2.getTitle()+"-----"+
blog2.getContent()+"-----"+blog2.getOwner());
}
}
@Test
public void queryForeachArray() throws IOException{
int[] array={1,2};
List<Blog> blogs=session.selectList("com.lq.model.BlogMapper.query_foreach_array", array);
for (Blog blog2 : blogs) {
System.out.println(blog2.getId()+"-----"+blog2.getTitle()+"-----"+
blog2.getContent()+"-----"+blog2.getOwner());
}
}
@Test
public void queryForeachMap() throws IOException{
Map map = new HashMap();
int[] array={1,2};
map.put("owner", "張三");
map.put("array",array);
List<Blog> blogs=session.selectList("com.lq.model.BlogMapper.query_foreach_map", map);
for (Blog blog2 : blogs) {
System.out.println(blog2.getId()+"-----"+blog2.getTitle()+"-----"+
blog2.getContent()+"-----"+blog2.getOwner());
}
}
}