update操作之set标签
直接上例子说明
//接口中的方法为int update(User user);
try { sqlSession = MyBatisUtil.getSqlSession(); User user = new User(); user.setId(3); user.setAccount("solider76"); user.setUser_name("士兵76号"); int num = sqlSession.getMapper(UserDao.class).update(user); sqlSession.commit(); System.out.println(num); } catch(Exception e){
throw new RuntimeException(e.getMessage());
} finally { MyBatisUtil.closeSqlSession(sqlSession); }
映射文件:
<update id="update" parameterType="self.exercise.bean.User"> update web_user <set> <if test="account!=null"> account = #{account}, </if> <if test="password!=null"> password = #{password}, </if> <if test="user_name!=null"> user_name =#{user_name} </if> </set> where id=#{id} </update>
set标签会自动检索最后一个逗号,并清除。
trim自定义标签
有时候如果有些标签用起来不尽人意,可以用trim标签自定义标签,比如where标签的等价trim元素为
<trim prefix="WHERE" prefixOverrides="and | or "> ... </trim>
执行trim标签时,会首先动态前置WHERE,并且通过prefixOverrides检索去掉无关的and 或or
而set标签的等价trim元素为
<trim prefix="SET" suffixOverrides=","> ... </trim>
首先会动态前置SET,并通过suffixOverrides去掉无关紧要的,
foreach标签
如果判断的条件在某个集合中,类似select * from web_user where id in(1,2,3,4)
此时需要使用foreach标签
//接口中的方法为List<User> foreach(int[] ids);
try { sqlSession = MyBatisUtil.getSqlSession(); Integer[] ids = new Integer[]{ 1 , 2 , 3 }; List<User> list = sqlSession.getMapper(UserDao.class).foreach01(ids); logger.debug(list); } finally { MyBatisUtil.closeSqlSession(sqlSession); }
映射文件:
<select id="foreach01" resultType="self.exercise.bean.User"> select * from web_user where id in <foreach collection="array" open="(" close=")" item="id" separator=","> #{id} </foreach> </select>
collection中可以写array、list、map中的key,具体是什么要看接口中的参数类型
DEBUG [main] - ==> Preparing: select * from web_user where id in ( ? , ? , ? ) DEBUG [main] - ==> Parameters: 1(Integer), 2(Integer), 3(Integer) TRACE [main] - <== Columns: id, account, password, user_name TRACE [main] - <== Row: 1, wukong, wukong, 悟空 TRACE [main] - <== Row: 2, wuneng, wuneng, 悟能 TRACE [main] - <== Row: 3, solider76, wujing, 士兵76号 DEBUG [main] - <== Total: 3