1、ResultMap高级结果映射
如果查询出的列名和属性名不一致,可以通过ResultMap做映射,放在statement的输出类型中
如下:
2、动态SQL,使用各种动态标签实现动态拼接sql,常用动态SQL标签有if、where、foreach
where 和 if 标签使用如下
<mapper namespace="com.hjp.mapper.UserMapper"> <select id="findUserByName" parameterType="User" resultType="User"> SELECT * FROM USER <!--where标签会去掉条件中的第一个AND符号,不能自己去掉AND--> <where> <if test="userName!=null and userName!=''"> AND username LIKE '%${userName}%' </if> </where> </select> </mapper>
测试代码如下
@Test public void func2() throws Exception { SqlSession session=factory.openSession(); UserMapper userMapper=session.getMapper(UserMapper.class); User user=new User(); user.setUserName("张"); List<User> users=userMapper.findUserByName(user); System.out.println(users); session.close(); }
where和foreach标签使用如下
<select id="findUserByIds" parameterType="List" resultType="User"> SELECT * FROM USER <where> <!--如果传入的参数是集合,collection必须为list;如果是对象,collection是对象中为集合的属性--> <foreach collection="list" item="id" open="and id in(" close=")" separator=","> #{id} </foreach> </where> </select>
测试代码如下
@Test public void func3() throws Exception { SqlSession session=factory.openSession(); UserMapper userMapper=session.getMapper(UserMapper.class); List<Integer> idList=new ArrayList<Integer>(); idList.add(1); idList.add(31); List<User> users=userMapper.findUserByIds(idList); System.out.println(users); session.close(); }
3、SQL片段,为了提高SQL的可重用性,可以使用sql标签来定义SQL片段
建议:SQL片段中的内容最后是以表单来定义(也就是依据表单来划分)、如果是查询字段,则不要写上SELECT,如果是条件语句,则不要写上WHERE
使用如下
<sql id="user_columns"> username,sex,birthday </sql> <sql id="user_where"> <foreach collection="list" item="id" open="and id in(" close=")" separator=","> #{id} </foreach> </sql> <select id="findUserByIds" parameterType="List" resultType="User"> SELECT <include refid="user_columns"></include> FROM USER <where> <include refid="user_where"></include> </where> </select>