MyBatis--03--输出结果封装

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);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值