resultType 配置结果类型
一. 基本类型示例
1. Dao 接口
/**
* 查询总记录条数
*/
int findTotal();
2. 映射配置
<!-- 查询总记录条数 -->
<select id="findTotal" resultType="int">
select count(*) from user;
</select>
二. 实体类类型示例
1. Dao 接口
/**
* 查询所有用户
*/
List<User> findAll();
2. 映射配置
<!-- 配置查询所有操作 -->
<select id="findAll" resultType="com.jess.domain.User">
select * from user
</select>
三. 特殊情况示例
1. 修改实体类
实体类代码如下:( 此时的实体类属性和数据库表的列名已经不一致了)
//省略get、set、tostring方法
public class User implements Serializable {
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
}
2. Dao 接口
/**
* 查询所有用户
*/
List<User> findAll();
4. 修改映射配置
<!-- 配置查询所有操作 -->
<select id="findAll" resultType="com.jess.domain.User">
select id as userId,username as userName,birthday as userBirthday,
sex as userSex,address as userAddress from user
</select>
5. 测试查询结果
@Test
public void testFindAll() {
List<User> users = userDao.findAll();
for(User user : users) {
System.out.println(user);
}
}
resultMap 结果类型
1. 定义 resultMap
<!-- 建立 User 实体和数据库表的对应关系
type 属性:指定实体类的全限定类名
id 属性:给定一个唯一标识,是给查询 select 标签引用用的。
-->
<resultMap type="com.jess.domain.User" id="userMap">
<id column="id" property="userId"/>
<result column="username" property="userName"/>
<result column="sex" property="userSex"/>
<result column="address" property="userAddress"/>
<result column="birthday" property="userBirthday"/>
</resultMap>
id 标签:用于指定主键字段
result 标签:用于指定非主键字段
column 属性:用于指定数据库列名
property 属性:用于指定实体类属性名称
2. 映射配置
<!-- 配置查询所有操作 -->
<select id="findAll" resultMap="userMap">
select * from user
</select>
3. 测试结果
@Test
public void testFindAll() {
List<User> users = userDao.findAll();
for(User user : users) {
System.out.println(user);
}
}