当SQL查询出的结果集封装成bean实体时,实体类中的字段和sql结果集字段不同,不匹配的字段无法封装到实体类中。
有两种结果方法:
1.可以在SQL语句中设置别名,进行匹配
2.可以使用 resultMap 标签自定义封装类型
第一种方式设置别名就不提啦,大家都会。下面来看看resultMap标签的自定义封装
User表
User实体类
/**
* User的实体类
* @see 该实体类中的字段 和 数据库User表中的字段 (id,name,money) 名称不相同
*/
public class UserEntity {
private Integer u_id;
private String u_name;
private Integer u_money;
private String sex;
//.....省略set 、 get 、toString 方法
}
User的持久层接口
/**
* User表的 DAO接口
* @author dell
*/
public interface UserMapper {
//通过 id查询指定 User
public UserEntity getUserEntityByid(Integer id);
}
UserMapper.xml 映射文件
<mapper namespace="com.mybatis.dao.UserMapper">
<!-- resultMap 自定义封装规则
id :设置封装标识 / type:封装的类型
-->
<resultMap id="UsEn" type="com.mybatis.bean.UserEntity" >
<!-- 指定封装主键的规则
column :表示数据库查询的结果集对应的字段
prorerty : 指定对应对象的字段名
-->
<id column="id" property="u_id"/>
<!-- 指定普通字段的封装规则 -->
<result column="name" property="u_name" />
<result column="money" property="u_money" />
<!-- 其余没有指定的字段,mybatis会自动封装(前提是数据库字段和实体类字段一样)
但是建议只要定义resultMap就建议全部定义好) -->
<!-- 还有sex字段,实体类和数据库字段名都一样,可以不指定,但是建议指定 -->
<result column="sex" property="sex"/>
</resultMap>
<!-- public User getUserEntityByid(Integer id); -->
<select id="getUserEntityByid" resultMap="UsEn"> <!-- 返回值使用 自定义封装规则-->
select * from User where id = #{id}
</select>
</mapper>
main
public static void main(String[] args) throws IOException {
String resource = "mybatis_config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
UserEntity entity = mapper.getUserEntityByid(1); //查询id为1 的User
System.out.println(entity.toString());
}
console 输出
UserEntity [u_id=1, u_name=tom, u_money=1200, sex=man]