1.1 resultType
使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。
如果查询出来的列名和pojo中的属性名全部不一致,没有创建pojo对象。
只要查询出来的列名和pojo中的属性有一个一致,就会创建pojo对象。
1.1.1 输出简单类型
1.1.1.1 需求
用户信息的综合查询列表总数,通过查询总数和上边用户综合查询列表才可以实现分页。
1.1.1.2 mapper.xml
<!-- 用户信息综合查询 -->
<select id="findUserCount" parameterType="com.xdy.mybatis.po.UserQueryVo"
resultType="int">
SELECT count(*) FROM USER WHERE user.sex=#{userCustom.sex} and user.username like '%${userCustom.username}%'
</select>
1.1.1.3 mapper.java
public int findUserCount(UserQueryVo userQueryVo) throws Exception;
1.1.1.4 测试代码
@Test
public void testFindUserCount() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
UserQueryVo userQueryVo = new UserQueryVo();
UserCustom userCustom = new UserCustom();
userCustom.setSex("1");
userCustom.setUsername("小明");
userQueryVo.setUserCustom(userCustom);
int count = userMapper.findUserCount(userQueryVo);
System.out.println(count);
}
1.1.1.5 小结
查询出来的结果集只有一行且一列,可以使用简单类型进行输出映射。
1.1.2 输出pojo对象和pojo列表
不管是输出的pojo单个对象还是一个列表(list中包括pojo),在mapper.xml中resultType指定的类型是一样的。
在mapper.java指定的方法返回值类型不一样:
1、输出单个pojo对象,方法返回值是单个对象类型
public User findUserById(int id) throws Exception;
2、输出pojo对象list,方法返回值是List<Pojo>
public List<User> findUserByName(String name) throws Exception;
生成的动态代理对象中是根据mapper方法的返回值类型确定是调用selectOne(返回单个对象调用)还是selectList (返回集合对象调用 ).
1.2 resultMap
mybatis中使用resultMap完成高级输出结果映射。
1.2.1 resultMap使用方法
如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。
1、定义resultMap
2、使用resultMap作为statement的输出映射类型
1.2.2 将下边的sql使用User完成映射
SELECT id id_,username username_ FROM USER WHERE id=#{value}
User类中属性名和上边查询列名不一致。
1.2.2.1 定义reusltMap
<resultMap type="user" id="userResultMap">
<id column="id_" property="id"/>
<result column="username_" property="username"/>
</resultMap>
type:resultMap最终映射的java对象类型,可以使用别名。
1.2.2.2 使用resultMap作为statement的输出映射类型
<select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
SELECT id id_,username username_ FROM USER WHERE id=#{value}
</select>
1.2.2.3 mapper.java
public User findUserByIdResultMap(int id) throws Exception;
1.2.2.4 测试
@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);
}
1.3 小结
使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。
如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。