Mybatis學習筆記(六)--動態sql拼接
阿新 • • 發佈:2019-01-08
介紹
通過mybatis提供的各種標籤方法實現動態拼接sql
Mybatis動態sql---<sql>與<include>
<!-- 使用include標籤載入sql片段;refid是sql片段id --> <sql id="select"> select * from user </sql> <!-- 在需要使用的地方使用include標籤使用 在後面的動態sql標籤中會使用到 這裡的refid與<sql>中的select是一一對應的 --> <include refid="select"/>
Mybatis動態sql---<if>標籤
mapper介面
public List<User> findUserBySexAndName(User user);
<!-- 動態SQL配置 有<if> 這裡是可以做一個判斷,配置上sql的值 <where> 這裡是可以去掉語句中的就第一個前and --> <!-- 根據性別和名字來查詢 --> <select id="findUserBySexAndName" parameterType="User" resultType="User"> <include refid="select"/> <where> <if test="sex != null and sex !=''"> and sex = #{sex} </if> <if test="username!=null and username!=''"> and username like '%${username}%' </if> </where> </select>
測試程式碼
@Test public void testFindUserBySexAndName() throws Exception { String resource = "SqlMapConfig.xml"; InputStream resourceAsStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User(); user.setSex("0"); user.setUsername("lin"); List<User> list = mapper.findUserBySexAndName(user); for (User user2 : list) { System.out.println(user2); } }
資料庫中的資料
測試效果
Mybatis動態sql---<foreach>
<!-- findUserByUserVo輸出類 -->
<select id="findUserByUserVolist" parameterType="UserVo" resultType="User">
<include refid="select"/>
<!-- foreach標籤,進行遍歷 -->
<!-- collection:遍歷的集合,這裡是QueryVo的ids屬性 -->
<!-- item:遍歷的專案,可以隨便寫,,但是和後面的#{}裡面要一致 -->
<!-- open:在前面新增的sql片段 -->
<!-- close:在結尾處新增的sql片段 -->
<!-- separator:指定遍歷的元素之間使用的分隔符 -->
<where>
id in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</where>
</select>
UserVo程式碼
package com.janson.vo;
import java.io.Serializable;
import java.util.List;
import com.janson.pojo.User;
public class UserVo implements Serializable {
private static final long serialVersionUID = 1L;
private User user;
private List<Integer> list;
private Integer[] ids;
。。。省略了get和set
}
mapper程式碼
public List<User> findUserByUserVolist(UserVo vo);
測試程式碼
@Test
public void testfindUserByUserVolist() throws Exception {
String resource = "SqlMapConfig.xml";
InputStream resourceAsStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
UserVo vo = new UserVo();
List l = new ArrayList<>();
l.add("1");
l.add("3");
l.add("4");
vo.setList(l);
List<User> list = mapper.findUserByUserVolist(vo);
for (User user : list) {
System.out.println(user);
}
}
測試結果