自动映射例子
当数据库名称与pojo一致时候,可以直接自动映射
<select id="selectUsers" resultType="com.someapp.model.User">
select id, username, hashedPassword
from some_table
where id = #{id}
</select>
当数据库名称与pojo不一致时候,采用类型别名,比如:
<select id="selectUsers" resultType="User">
select
user_id as "id",
user_name as "userName",
hashed_password as "hashedPassword"
from some_table
where id = #{id}
</select>
ResultMap设计
使用外部的 resultMap 会怎样,解决列名不匹配的另外一种方式。
数据库column -> java pojo property
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id" />
<result property="username" column="user_name"/>
<result property="password" column="hashed_password"/>
</resultMap>
其中id表示主键,对应xml文件可配置如下
<select id="selectUsers" resultMap="userResultMap">
select user_id, user_name, hashed_password
from some_table
where id = #{id}
</select>
ResultMap高级结果映射
pojo对象
public class Employee {
private Integer id;
private String realName;
private SexEnum sex;
private Date birthday;
private String mobile;
private String email;
private String position;
private String note;
private WorkCard workCard;
private List<EmployeeTask> employeeTasks;
}
xml配置文件
<resultMap id="BaseResultMap" type="priv.dengjl.ns.bean.Employee">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="real_name" jdbcType="VARCHAR" property="realName" />
<result column="sex" typeHandler="priv.dengjl.ns.handler.SexEnumHandler"
property="sex" />
<result column="birthday" jdbcType="DATE" property="birthday" />
<result column="mobile" jdbcType="VARCHAR" property="mobile" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="position" jdbcType="VARCHAR" property="position" />
<result column="note" jdbcType="VARCHAR" property="note" />
<association column="id" property="workCard"
select="priv.dengjl.ns.mapper.WorkCardMapper.getWorkCardByEmpId" />
<collection column="id" property="employeeTasks"
select="priv.dengjl.ns.mapper.EmployeeTaskMapper.getEmployeeTaskListByEmpId" />
<discriminator column="sex" javaType="int">
<case value="1" resultMap="MaleEmployeeMap"/>
<case value="0" resultMap="FemaleEmployeeMap"/>
</discriminator>
</resultMap>
一对一 workCard对象
<association column="id" property="workCard"
select="priv.dengjl.ns.mapper.WorkCardMapper.getWorkCardByEmpId" />
一对多 workCard对象
<association column="id" property="workCard"
select="priv.dengjl.ns.mapper.WorkCardMapper.getWorkCardByEmpId" />
鉴别器
<discriminator column="sex" javaType="int">
<case value="1" resultMap="MaleEmployeeMap"/>
<case value="0" resultMap="FemaleEmployeeMap"/>
</discriminator>
其中select对应的值为单个文件的xml配置
1