GVKun编程网logo

mybatis(1)听课笔记12.10,动态sql

13

在这篇文章中,我们将为您详细介绍mybatis(1)听课笔记12.10,动态sql的内容。此外,我们还会涉及一些关于JavaEE_Mybatis_SpringMVC__Mybatis_lesson8_

在这篇文章中,我们将为您详细介绍mybatis(1)听课笔记12.10,动态sql的内容。此外,我们还会涉及一些关于JavaEE_Mybatis_SpringMVC__Mybatis_lesson8_Mybatis的动态sql、Mybatis - 3 动态sql、Mybatis - 动态sql、Mybatis -- 动态sql的知识,以帮助您更全面地了解这个主题。

本文目录一览:

mybatis(1)听课笔记12.10,动态sql

mybatis(1)听课笔记12.10,动态sql

sqlMapConfig 配置文件的优化:

定义db,properties配置文件

 

 

 

第二种

 

mapper标签的优化

Mybatis连接池与事务深入:

true 设置自动提交

 

动态sql:

if标签

 where 标签

foreach标签

 

批处理

 

JavaEE_Mybatis_SpringMVC__Mybatis_lesson8_Mybatis的动态sql

JavaEE_Mybatis_SpringMVC__Mybatis_lesson8_Mybatis的动态sql

项目代码

http://pan.baidu.com/s/1c01BLvi


Mybatis中  拼接动态SQL,让SQL根据传递进来的参数,进行动态的拼接,拼成指定条件的语句


0.配置文件

1.userMapper.java (Dao接口)

2.userMapper.xml  (Dao实现)   1,2是通过配置文件中 批量加载mapper 的方式联系的。(package的方式) 

注意

(1) xxxMapper.xml 需要与 xxxMapper.java 名称相同,

(2)且放到同一文件夹下面。

动态SQL写在 userMapper.xml 里面:

  通过类似于JSTL标签的表现方式

<!-- where 可以自动去掉第一个and  -->

	<!--
	通过OGNL的方式进行获取 
	 -->
	<select id="findUserList" parameterType="cn.itcast.mybatis.po.UserQueryVo"
	resultType="cn.itcast.mybatis.po.UserCustom">
		SELECT * FROM user 
		<!--
		where 可以自动去掉第一个and 
		 -->
		<where>
			<if test="userCustom!=null">
				<if test="userCustom.sex!=null and userCustom.sex!=''">
					AND user.sex = #{userCustom.sex}
				</if>
				<if test="userCustom.username!=null and userCustom.username!=''">
					AND user.username like'%${userCustom.username}%'
				</if>
			</if>
		</where>
	</select>



3.User.java (ORM)

4.UserCustom.java(po类)

5.UserQueryVo(vo类)

tips:

(1) Vo 视图层面的对象

(2) Po 持久层面的对象

(3) Pojo 用户自定义的对象,综合了Vo与Po的JavaBean

6.junit 单元测试




文档目录结构



0.配置文件

db.properties

[plain]  view plain copy print ?
  1. jdbc.driver=com.mysql.jdbc.Driver  
  2. jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8  
  3. jdbc.username=root  
  4. jdbc.password=123456  



SqlMapConfig.xml

[plain]  view plain copy print ?
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE configuration  
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  5. <configuration>  
  6.     <!-- 加载属性文件 -->  
  7.     <properties resource="db.properties"></properties>  
  8.     <!--   
  9.     <settings></settings>  
  10.      -->  
  11.     <typeAliases>  
  12.         <!--  
  13.         <typeAlias type="cn.itcast.mybatis.po.User" alias="user"/>   
  14.          -->  
  15.          <!-- 批量定义别名 -->  
  16.         <package name="cn.itcast.mybatis.po"/>  
  17.     </typeAliases>  
  18.     <!-- 和spring整合后 environments配置将废除-->  
  19.     <environments default="development">  
  20.         <environment id="development">  
  21.         <!-- 使用jdbc事务管理-->  
  22.             <transactionManager type="JDBC" />  
  23.         <!-- 数据库连接池-->  
  24.             <dataSource type="POOLED">  
  25.                 <property name="driver" value="${jdbc.driver}" />  
  26.                 <property name="url" value="${jdbc.url}" />  
  27.                 <property name="username" value="${jdbc.username}" />  
  28.                 <property name="password" value="${jdbc.password}" />  
  29.             </dataSource>  
  30.         </environment>  
  31.     </environments>  
  32.     <mappers>  
  33.         <mapper resource="sqlmap/User.xml"/>  
  34.         <!--   
  35.         <mapper resource="mapper/UserMapper.xml"/>  
  36.          -->  
  37.         <!--  
  38.         <mapper />   
  39.          -->  
  40.         <package name="cn.itcast.mybatis.mapper"/>  
  41.           
  42.     </mappers>  
  43. </configuration>  


1.userMapper.java (Dao接口)

[plain]  view plain copy print ?
  1. package cn.itcast.mybatis.mapper;  
  2.   
  3. import java.util.List;  
  4.   
  5. import cn.itcast.mybatis.po.User;  
  6. import cn.itcast.mybatis.po.UserCustom;  
  7. import cn.itcast.mybatis.po.UserQueryVo;  
  8.   
  9. public interface UserMapper {  
  10.   
  11.     List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;  
  12.   
  13.     User findUserById(Integer id) throws Exception;  
  14.   
  15.     public List<User> findUserByName(String name) throws Exception;  
  16.   
  17.     void insertUser(User user) throws Exception;  
  18.   
  19.     void deleteUser(int id) throws Exception;  
  20.   
  21. }  


2.userMapper.xml  (Dao实现)

<?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">

<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 
注意:使用mapper代理方法开发,namespace有特殊重要的作用-->
<mapper namespace="cn.itcast.mybatis.mapper.UserMapper">

	<resultMap type="User" id="userResultMap">
		<id column="_id" property="id"/>
		<result column="_username" property="username"/>
	</resultMap>
	
	<!--
	通过OGNL的方式进行获取 
	 -->
	<select id="findUserList" parameterType="cn.itcast.mybatis.po.UserQueryVo"
	resultType="cn.itcast.mybatis.po.UserCustom">
		SELECT * FROM user 
		<!--
		where 可以自动去掉第一个and 
		 -->
		<where>
			<if test="userCustom!=null">
				<if test="userCustom.sex!=null and userCustom.sex!=''">
					AND user.sex = #{userCustom.sex}
				</if>
				<if test="userCustom.username!=null and userCustom.username!=''">
					AND user.username like'%${userCustom.username}%'
				</if>
			</if>
		</where>
	</select>

	<select id="findUserCount" parameterType="cn.itcast.mybatis.po.UserQueryVo"
	resultType="int">
		SELECT COUNT(*) FROM user WHERE user.sex = #{userCustom.sex} AND user.username like'%${userCustom.username}%'
		<!--
		where 可以自动去掉第一个and 
		 -->
		<where>
			<if test="userCustom!=null">
				<if test="userCustom.sex!=null and userCustom.sex!=''">
					AND user.sex = #{userCustom.sex}
				</if>
				<if test="userCustom.username!=null and userCustom.username!=''">
					AND user.username like'%${userCustom.username}%'
				</if>
			</if>
		</where>
	</select>
	
	<!-- 利用resultMap作为返回值返回参数 -->
	<select id="findUserByIdResultMap" parameterType="java.lang.Integer" resultMap="userResultMap">
	 	SELECT id _id, username _username FROM user where id = #{id} 
	</select>
	
	<!-- 在 映射文件中配置很多sql语句 -->
	<!-- 需求:通过id查询用户表的记录 -->
	<!-- 通过 select执行数据库查询
	id:标识 映射文件中的 sql
	将sql语句封装到mappedStatement对象中,
	=====================所以将id称为statement的id
	parameterType:指定输入 参数的类型,这里指定int型 
	#{}表示一个占位符号
	
	#{id}:其中的
	====================id表示接收输入 的参数,参数名称就是id,
	====================如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称
	#{},
	resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。
	 -->
	 <!-- cn.itcast.mybatis.po.User -->
	 <select id="findUserById" parameterType="java.lang.Integer" resultType="user">
	 	SELECT * FROM user where id = #{id} 
	 </select>
	 
	 
	 
	<!-- 根据用户名称模糊查询用户信息,可能返回多条
	resultType:指定就是单条记录所映射的java对象 类型
	${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。
	=============使用${}拼接sql,引起 sql注入
	=============${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value
	 --> 
	 <select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User">
	 	SELECT * FROM user where username like '%${value}%'
	 </select>
	 
	 
	 <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
	 	<!-- 
		将插入数据的主键返回,返回到user对象中
		
		=================SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键
		
		keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性
		orderSELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
		resultType:指定SELECT LAST_INSERT_ID()的结果类型
		 -->
	 	<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
	 		SELECT LAST_INSERT_ID()
	 	</selectKey>
	 	INSERT INTO user(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address}) 
	 	<!-- 
		使用mysql的uuid()生成主键
		执行过程:
		首先通过uuid()得到主键,将主键设置到user对象的id属性中
		其次在insert执行时,从user对象中取出id属性值
		 -->
		<!--  <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
			SELECT uuid()
		</selectKey>
		insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address}) -->
	 </insert>
	 	
	<!-- 删除 用户
	根据id删除用户,需要输入 id值
	 -->
	<delete id="deleteUser" parameterType="java.lang.Integer">
		DELETE FROM user WHERE id=#{id}
	</delete>
	 
	<!-- 根据id更新用户
	分析:
	需要传入用户的id
	需要传入用户的更新信息
	parameterType指定user对象,包括 id和更新信息,注意:id必须存在
	#{id}:从输入 user对象中获取id属性值
	 -->
	<update id="updateUser"	parameterType="cn.itcast.mybatis.po.User">
		UPDATE user SET username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} 
		WHERE id=#{id}
	</update>
	 
</mapper>



3.User.java (ORM)

[java]  view plain copy print ?
  1. package cn.itcast.mybatis.po;  
  2.   
  3. import java.util.Date;  
  4.   
  5. //hibernate字段名和属性名相对应  
  6. public class User {  
  7.     @Override  
  8.     public String toString() {  
  9.         return "User [id=" + id + ", username=" + username + ", birthday="  
  10.                 + birthday + ", sex=" + sex + ", address=" + address + "]";  
  11.     }  
  12.   
  13.     private int id;  
  14.     private String username;  
  15.     private Date birthday;  
  16.     private String sex;  
  17.     private String address;  
  18.   
  19.     public int getId() {  
  20.         return id;  
  21.     }  
  22.   
  23.     public void setId(int id) {  
  24.         this.id = id;  
  25.     }  
  26.   
  27.     public String getUsername() {  
  28.         return username;  
  29.     }  
  30.   
  31.     public void setUsername(String username) {  
  32.         this.username = username;  
  33.     }  
  34.   
  35.     public Date getBirthday() {  
  36.         return birthday;  
  37.     }  
  38.   
  39.     public void setBirthday(Date birthday) {  
  40.         this.birthday = birthday;  
  41.     }  
  42.   
  43.     public String getSex() {  
  44.         return sex;  
  45.     }  
  46.   
  47.     public void setSex(String sex) {  
  48.         this.sex = sex;  
  49.     }  
  50.   
  51.     public String getAddress() {  
  52.         return address;  
  53.     }  
  54.   
  55.     public void setAddress(String address) {  
  56.         this.address = address;  
  57.     }  
  58.   
  59. }  



4.UserCustom.java(po类)

[java]  view plain copy print ?
  1. package cn.itcast.mybatis.po;  
  2.   
  3. /** 
  4.  * <p> 
  5.  * Description:用户的扩展类 
  6.  * </p> 
  7.  *  
  8.  * @author szh 
  9.  */  
  10. public class UserCustom extends User {  
  11.     // 可以扩展用户的信息  
  12. }  




5.UserQueryVo(vo类)

[java]  view plain copy print ?
  1. package cn.itcast.mybatis.po;  
  2.   
  3. /** 
  4.  *  
  5.  * @author szh 
  6.  *  
  7.  */  
  8. public class UserQueryVo {  
  9.     private UserCustom userCustom;  
  10.   
  11.     public UserCustom getUserCustom() {  
  12.         return userCustom;  
  13.     }  
  14.   
  15.     public void setUserCustom(UserCustom userCustom) {  
  16.         this.userCustom = userCustom;  
  17.     }  
  18.   
  19.     // 可以包装其他的查询条件,订单,商品  
  20. }  


6.junit 单元测试

package cn.itcast.mybatis.mapper;
  • import java.io.InputStream;
  • import java.util.List;
  • 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.Before;
  • import org.junit.Test;
  • import cn.itcast.mybatis.po.User;
  • import cn.itcast.mybatis.po.UserCustom;
  • import cn.itcast.mybatis.po.UserQueryVo;
  • public class UserMapperTest {
  • private SqlSessionFactory sqlSessionFactory;
  • // 此方法是在执行testFindUserById之前执行
  • @Before
  • public void setUp() throws Exception {
  • String resource = null; // mybatis全局配置文件
  • InputStream inputStream = null; // 输入流
  • try {
  • // mybatis配置文件
  • resource = "SqlMapConfig.xml";
  • inputStream = Resources.getResourceAsStream(resource);
  • // 创建会话工厂,传入mybatis配置文件信息
  • // 创建sqlSessionFactory
  • this.sqlSessionFactory = new SqlSessionFactoryBuilder()
  • .build(inputStream);
  • } catch (Exception e) {
  • e.printStackTrace();
  • }
  • }
  • @Test
  • public void testFindUserById() throws Exception {
  • SqlSession sqlSession = sqlSessionFactory.openSession();
  • UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  • User user = userMapper.findUserById(1);
  • System.out.println(user);
  • sqlSession.close();
  • }
  • @Test
  • public void testFindUserByIdResultMap() throws Exception {
  • SqlSession sqlSession = sqlSessionFactory.openSession();
  • UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  • User user = userMapper.findUserByIdResultMap(1);
  • System.out.println(user);
  • sqlSession.close();
  • }
  • @Test
  • public void testFindUserByName() throws Exception {
  • SqlSession sqlSession = sqlSessionFactory.openSession();
  • // 创建UserMapper对象,mybatis自动生成mapper代理对象
  • UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  • List<User> userList = userMapper.findUserByName("小");
  • System.out.println(userList);
  • sqlSession.close();
  • }
  • @Test
  • public void testFindUserList() throws Exception {
  • SqlSession sqlSession = null;
  • try {
  • sqlSession = sqlSessionFactory.openSession();
  • // 创建UserMapper对象,mybatis 自动生成mapper代理对象
  • UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  • UserQueryVo userQueryVo = new UserQueryVo();
  • UserCustom userCustom = new UserCustom();
  • // userCustom.setSex("1");
  • // userCustom.setUsername("小");
  • userQueryVo.setUserCustom(userCustom);
  • // userQueryVo
  • List<UserCustom> list = userMapper.findUserList(null);
  • System.out.println(list);
  • } catch (Exception e) {
  • e.printStackTrace();
  • } finally {
  • sqlSession.close();
  • }
  • }
  • @Test
  • public void testFindUserCount() throws Exception {
  • SqlSession sqlSession = null;
  • try {
  • sqlSession = sqlSessionFactory.openSession();
  • // 创建UserMapper对象,mybatis 自动生成mapper代理对象
  • UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  • UserQueryVo userQueryVo = new UserQueryVo();
  • UserCustom userCustom = new UserCustom();
  • userCustom.setSex("1");
  • userCustom.setUsername("小");
  • userQueryVo.setUserCustom(userCustom);
  • Integer count = userMapper.findUserCount(userQueryVo);
  • System.out.println(count);
  • } catch (Exception e) {
  • e.printStackTrace();
  • } finally {
  • sqlSession.close();
  • }
  • }
  • @Test
  • public void testInsertUser() throws Exception {
  • SqlSession sqlSession = null;
  • try {
  • sqlSession = sqlSessionFactory.openSession();
  • // 创建UserMapper对象,mybatis自动生成mapper代理对象
  • UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  • User user = new User();
  • user.setUsername("hahak");
  • userMapper.insertUser(user);
  • sqlSession.commit();
  • } catch (Exception e) {
  • e.printStackTrace();
  • } finally {
  • sqlSession.close();
  • }
  • }
  • @Test
  • public void testDeleteUser() throws Exception {
  • SqlSession sqlSession = null;
  • try {
  • sqlSession = sqlSessionFactory.openSession();
  • // 创建UserMapper对象,mybatis 自动生成mapper代理对象
  • UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  • userMapper.deleteUser(36);
  • sqlSession.commit();
  • } catch (Exception e) {
  • e.printStackTrace();
  • } finally {
  • sqlSession.close();
  • }
  • }
  • }


  • 重要测试代码:

    	@Test
    	public void testFindUserList() throws Exception {
    		SqlSession sqlSession = null;
    		try {
    			sqlSession = sqlSessionFactory.openSession();
    			// 创建UserMapper对象,mybatis 自动生成mapper代理对象
    			UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    
    			UserQueryVo userQueryVo = new UserQueryVo();
    			UserCustom userCustom = new UserCustom();
    			// userCustom.setSex("1");
    			// userCustom.setUsername("小");
    			userQueryVo.setUserCustom(userCustom);
    
    			// userQueryVo
    			List<UserCustom> list = userMapper.findUserList(null);
    			System.out.println(list);
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			sqlSession.close();
    		}
    	}
    
    	@Test
    	public void testFindUserCount() throws Exception {
    		SqlSession sqlSession = null;
    		try {
    			sqlSession = sqlSessionFactory.openSession();
    			// 创建UserMapper对象,mybatis 自动生成mapper代理对象
    			UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    
    			UserQueryVo userQueryVo = new UserQueryVo();
    			UserCustom userCustom = new UserCustom();
    			userCustom.setSex("1");
    			userCustom.setUsername("小");
    			userQueryVo.setUserCustom(userCustom);
    
    			Integer count = userMapper.findUserCount(userQueryVo);
    			System.out.println(count);
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			sqlSession.close();
    		}
    	}



    单元测试结果

    对   List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception; 进行的测试






    Mybatis - 3 动态sql

    Mybatis - 3 动态sql

    动态sql

    2.1 where自动删首and

    2.2 set自动删尾逗号,

    2.3 choose-when相当于java中的switch-case,otherwise不是必要的

    2.4 使用select时需要指定resultType或者resultMap

    2.5 trim可以代替where和set使用

    2.6 foreach多用于in后

    2.7 include可以提高代码复用但是降低代码可读性

    <?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.bjsxt.mapper.StudentMapper">
    	<select id="selectByChoose" resultType="Student">
    		select id,name,age,score from student 
    		<where>
    			<choose>
    				<when test="name != null and name !=''''">
    					and name like ''%'' #{name} ''%''
    				</when>
    				<when test="age > 0">
    					and age >#{age}
    				</when>
    				<otherwise>
    					and 1=1
    				</otherwise>
    			</choose>
    				 
    		</where>
    	</select>
    	
    	<update id="updateBySet">
    		update student 
    		<set>
    			<if test="name != null and name !=''''">
    				name=#{name},
    			</if>
    			<if test="age > 0">
    				age=#{age},
    			</if>
    			<if test="score > 0">
    				score=#{score}
    			</if>
    		</set> 
    			where id=#{id}
    		
    	</update>
    	
    	<select id="selectByTrim" resultType="Student">
    		select id,name,age,score from student 
    		<trim prefix="where" prefixOverrides="AND |OR">
    			<if test="name != null and name !=''''">
    				and name like ''%'' #{name} ''%''
    			</if>
    			<if test="age > 0">
    				and age>#{age}
    			</if>
    			
    		</trim>
    		
    	</select>
    	
    	<update id="updateByTrim">
    		update student 
    		<trim prefix="set" suffixOverrides=",">
    			<if test="name != null and name !=''''">
    				name=#{name},
    			</if>
    			<if test="age > 0">
    				age=#{age},
    			</if>
    			<if test="score > 0">
    				score=#{score}
    			</if>
    		</trim>
    			where id=#{id}
    		
    	</update>
    	
    	<select id="forEachArray" resultType="Student">
    		<!-- select id,name,age,score from student where id in(1,2) -->
    		select id,name,age,score from student 
    		<if test="array.length >0">
    			where id in 
    			<foreach collection="array" item="myid" open="(" close=")" separator=",">
    				#{myid}
    			</foreach>
    		</if>
    	</select>
    	
    	<select id="forEachList" resultType="Student">
    		<!-- select id,name,age,score from student where id in(1,2) -->
    		select id,name,age,score from student 
    		<if test="list.size >0">
    			where id in 
    			<foreach collection="list" item="myid" open="(" close=")" separator=",">
    				#{myid}
    			</foreach>
    		</if>
    	</select>
    	
    	<select id="forEachList1" resultType="Student">
    		<!-- select id,name,age,score from student where id in(1,2) -->
    		<include refid="selectAll"/> from student 
    		<if test="list.size >0">
    			where id in 
    			<foreach collection="list" item="stu" open="(" close=")" separator=",">
    				#{stu.id}
    			</foreach>
    		</if>
    	</select>
    	
    	<sql id="selectAll">
    		select id,name,age,score
    	</sql>
    </mapper>

    Mybatis - 动态sql

    Mybatis - 动态sql

    1、动态sql:if 语句

    如果 #{username} 为空,那么查询结果也是空,如何解决这个问题呢?使用 if 来判断

    <select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
        select * from user where
            <if test="username != null">
               username=#{username}
            </if>
             
            <if test="username != null">
               and sex=#{sex}
            </if>
    </select>

    2、动态sql:if+where 语句

    <select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
        select * from user
        <where>
            <if test="username != null">
               username=#{username}
            </if>
             
            <if test="username != null">
               and sex=#{sex}
            </if>
        </where>
    </select>

    这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

    3、动态sql:if+set 语句

    同理,上面的对于查询 sql 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?

    <!-- 根据 id 更新 user 表的数据 -->
    <update id="updateUserById" parameterType="com.ys.po.User">
        update user u
            <set>
                <if test="username != null and username != ''">
                    u.username = #{username},
                </if>
                <if test="sex != null and sex != ''">
                    u.sex = #{sex}
                </if>
            </set>
         
         where id=#{id}
    </update>

    4、动态sql:choose(when,otherwise) 语句

    有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

    <select id="selectUserByChoose" resultType="com.ys.po.User" parameterType="com.ys.po.User">
          select * from user
          <where>
              <choose>
                  <when test="id !='' and id != null">
                      id=#{id}
                  </when>
                  <when test="username !='' and username != null">
                      and username=#{username}
                  </when>
                  <otherwise>
                      and sex=#{sex}
                  </otherwise>
              </choose>
          </where>
      </select>

    5、动态sql:trim 语句

     trim标记是一个格式化的标记,可以完成set或者是where标记的功能

      ①、用 trim 改写上面第二点的 if+where 语句

    <select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
            select * from user
            <!-- <where>
                <if test="username != null">
                   username=#{username}
                </if>
                 
                <if test="username != null">
                   and sex=#{sex}
                </if>
            </where>  -->
            <trim prefix="where" prefixOverrides="and | or">
                <if test="username != null">
                   and username=#{username}
                </if>
                <if test="sex != null">
                   and sex=#{sex}
                </if>
            </trim>
        </select>

    prefix:前缀      

      prefixoverride:去掉第一个and或者是or

     

    ②、用 trim 改写上面第三点的 if+set 语句

    <!-- 根据 id 更新 user 表的数据 -->
        <update id="updateUserById" parameterType="com.ys.po.User">
            update user u
                <!-- <set>
                    <if test="username != null and username != ''">
                        u.username = #{username},
                    </if>
                    <if test="sex != null and sex != ''">
                        u.sex = #{sex}
                    </if>
                </set> -->
                <trim prefix="set" suffixOverrides=",">
                    <if test="username != null and username != ''">
                        u.username = #{username},
                    </if>
                    <if test="sex != null and sex != ''">
                        u.sex = #{sex},
                    </if>
                </trim>
             
             where id=#{id}
        </update>

    suffix:后缀  

      suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)

    6、动态sql: sql 片段

    有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

      比如:假如我们需要经常根据用户名和性别来进行联合查询,那么我们就把这个代码抽取出来,如下:

    <!-- 定义 sql 片段 -->
    <sql id="selectUserByUserNameAndSexsql">
        <if test="username != null and username != ''">
            AND username = #{username}
        </if>
        <if test="sex != null and sex != ''">
            AND sex = #{sex}
        </if>
    </sql>

    引用 sql 片段

    <select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
        select * from user
        <trim prefix="where" prefixOverrides="and | or">
            <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
            <include refid="selectUserByUserNameAndSexsql"></include>
            <!-- 在这里还可以引用其他的 sql 片段 -->
        </trim>
    </select>

    注意:①、最好基于 单表来定义 sql 片段,提高片段的可重用性

         ②、在 sql 片段中最好不要包括 where 

    7、动态sql: foreach 语句

     需求:我们需要查询 user 表中 id 分别为1,2,3的用户

      sql语句:select * from user where id=1 or id=2 or id=3

           select * from user where id in (1,2,3)

    ①、建立一个 UserVo 类,里面封装一个 List<Integer> ids 的属性

    package com.ys.vo;
     
    import java.util.List;
     
    public class UserVo {
        //封装多个用户的id
        private List<Integer> ids;
     
        public List<Integer> getIds() {
            return ids;
        }
     
        public void setIds(List<Integer> ids) {
            this.ids = ids;
        }
     
    }  

    ②、我们用 foreach 来改写 select * from user where id=1 or id=2 or id=3

    <select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
        select * from user
        <where>
            <!--
                collection:指定输入对象中的集合属性
                item:每次遍历生成的对象
                open:开始遍历时的拼接字符串
                close:结束时拼接的字符串
                separator:遍历对象之间需要拼接的字符串
                select * from user where 1=1 and (id=1 or id=2 or id=3)
              -->
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id=#{id}
            </foreach>
        </where>
    </select>

    ③、我们用 foreach 来改写 select * from user where id in (1,2,3)

    <select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
            select * from user
            <where>
                <!--
                    collection:指定输入对象中的集合属性
                    item:每次遍历生成的对象
                    open:开始遍历时的拼接字符串
                    close:结束时拼接的字符串
                    separator:遍历对象之间需要拼接的字符串
                    select * from user where 1=1 and id in (1,2,3)
                  -->
                <foreach collection="ids" item="id" open="and id in (" close=") " separator=",">
                    #{id}
                </foreach>
            </where>
        </select>

     

    Mybatis -- 动态sql

    Mybatis -- 动态sql

    1 if判断标签

    test 里面是 条件

       trim 

     清除前缀

     清除 后缀

       添加 前缀 

     

      添加 后缀 

    where

     

     

     

    set

     

       foreach

     

     

            choose 标签 

      就是 switch  

     when 是选择 条件

    otherwise 作为补充

     

     sql 提取  处理*

     

     

    关于mybatis(1)听课笔记12.10,动态sql的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于JavaEE_Mybatis_SpringMVC__Mybatis_lesson8_Mybatis的动态sql、Mybatis - 3 动态sql、Mybatis - 动态sql、Mybatis -- 动态sql的相关知识,请在本站寻找。

    本文标签:

    上一篇mybatis-plus和pageHelper 设置关闭分页(mybatis plus page分页)

    下一篇Mybatis学习--入门(mybatis入门教程)