resultType
resultType是最常用的指定输入参数类型的方式,一般用来指定输出简单类型和pojo。
一、指定输出简单类型
映射文件:
<select id="findUserByUserName" parameterType="string" resultType="int"> select count(*) from user where username =#{username} </select>
实现:
/** * 根据姓名查询用户数量 * @param username * @return * @throws Exception */ @Override public int findUserByUserName(String username) throws Exception { SqlSession session=sqlSessionFactory.openSession(); int result=session.selectOne("com.danny.mybatis.findUserByUserName",username); session.close(); return result; }
测试:
@Test public void testQueryByUserName() throws Exception { UserDao userDao = new UserDaoImpl(sqlSessionFactory); int result = userDao.findUserByUserName("DannyHoo"); System.out.println(result); }
二、指定输入pojo
用resultType指定输入参数的类型为pojo时,有三种情况:
1、查询出来的列名与pojo中的属性名完全一致,结果会创建pojo对象,映射成功。
User.java
public class User implements Serializable { private int id; private String username; private int sex; private Date birthday; private String address; //getter、setter }
映射文件:
<select id="findUserById" parameterType="int" resultType="com.danny.mybatis.po.User"> select id,username,sex,birthday,address from user where id=#{value} </select>
当查询的字段与User的属性名完全一致时,查询结果会自动映射为pojo对象,且每个属性都会有值,如下:
2、查询出来的列名与pojo中的属性名部分一致,查询结果会自动映射为pojo对象,且部分属性会有值;
映射文件:
<select id="findUserById" parameterType="int" resultType="com.danny.mybatis.po.User"> select id,username as name,sex as,birthday as birthdate,address from user where id=#{value} </select>
3、查询出来的列名与pojo中的属性名完全不一致,则不会创建对象,结果为null;
<select id="findUserById" parameterType="int" resultType="com.danny.mybatis.po.User"> select id as number,username as name,sex as s,birthday as birthdate,address as addr from user where id=#{value} </select>
这时,输出的user直接为null:
需要注意的是,当输出类型为pojo时,不管查询结果为单个pojo对象还是集合,resultType的属性值都写成pojo的类型。
resultType还可以指定输出类型为Map,当指定输出类型为Map时,默认映射的结果集中列名为key值,查询到的数据为value。
resultMap
上面resultType指定输出类型为pojo时,查询结果集的列名可能与pojo的字段不一致,因此可以使用resultMap为列名和pojo的字段之间作一个映射关系。
比如上面的第2中情况,用resultType指定输出类型为pojo时,查询出来的列名与pojo中的属性名部分一致,查询结果会自动映射为pojo对象,但只有部分属性会有值。可以利用resultMap为其余不对应的列名与字段建立映射关系,使最终查询到的每列的值都可以一 一对应到pojo对象中。
映射文件:
<!--定义User的resultMap--> <resultMap type="com.danny.mybatis.po.User" id="userResultMap"> <id column="name" property="username"/> <id column="birthdate" property="birthday"/> </resultMap> <!--User查询语句--> <select id="findUserById" parameterType="int" resultMap="userResultMap"> select id,username as name,sex,birthday as birthdate,address from user where id=#{value} </select>
如上,在<select></select>的同级添加<resultMap></resultMap>标签,为两个不对应的属性配置映射关系。
配置后,查询结果如下:
总结
使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。
如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。



