MyBatis案例八:动态sql:set

MyBatis案例八:动态sql:set

  1. 接口方法:
public int updateByExample(Dept dept);
  1. mapper:
<update id="updateByExample">
		update dept		
		<trim prefix="set" suffixOverrides=",">
			<if test="dname != null">
				dname = #{dname},
			</if>
			<if test="loc != null">
				loc = #{loc},
			</if>
		</trim>
		where deptno = #{no}
	</update>

3.测试类:

	@Test
	public void testUpdateByExample() throws IOException {
		int n = mapper.updateByExample(new Dept(12,"人力资源部", "上海"));

		session.commit();// 提交事务
		System.out.println(n);
	}

4.改进:set

<update id="updateByExample">
		update dept		
		<set>
			<if test="dname != null">
				dname = #{dname},
			</if>
			<if test="loc != null">
				loc = #{loc},
			</if>
		</set>
		where deptno = #{no}
	</update>

练习:动态sql:动态插入

  1. 接口方法:
public int insertByExample(Dept dept);
  1. mapper:
<insert id="insertByExample">
		insert into dept
		<trim prefix="(" suffix=")" suffixOverrides=",">
			deptno,
			<if test="dname != null">
				dname,
			</if>
			<if test="loc != null">
				loc,
			</if>
		</trim>
		values
		<trim prefix="(" suffix=")" suffixOverrides=",">
			#{no},
			<if test="dname != null">
				#{dname},
			</if>
			<if test="loc != null">
				#{loc},
			</if>
		</trim>
	</insert>
  1. 测试代码中:
	@Test
	public void testInsertByExample() throws IOException {
		int n = mapper.insertByExample(new Dept(13, "hr", null));

		session.commit();// 提交事务
		System.out.println(n);
	}

猜你喜欢

转载自blog.csdn.net/pcbhyy/article/details/83715550