1. 程式人生 > >mybatis resultmap對映結果集(xml對映配置一)

mybatis resultmap對映結果集(xml對映配置一)

自動對映例子

當資料庫名稱與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