1. 程式人生 > >Mybatis 關聯查詢

Mybatis 關聯查詢

lec repo serial 嵌套 resultmap pub extend alt heal

一對一

一對一關聯查詢分為兩種方式:一種為嵌套結果查詢,一種為嵌套條件查詢(推薦使用)

利用User實體類和Position實體類為例:

User實體類

public class User implements Serializable{
private Integer id; private String userName; private String realName; private Byte sex; private String mobile; private String email;
private String note; private TPosition position; private TPosition position2; private List<TJobHistory> jobs ; private List<HealthReport> healthReports; private List<TRole> roles; 省略get set方法 }

Position實體類

public
class Position { private Integer id; private String postName; private String note; 省略get set 方法 }

XML配置(嵌套結果)

<!-- BaseResultMap -->
<resultMap id="BaseResultMap" type="TUser">
    <id column="id" property="id" />
    <result column
="user_name" property="userName" /> <result column="real_name" property="realName" /> <result column="sex" property="sex" /> <result column="mobile" property="mobile" /> <result column="email" property="email" /> <result column="note" property="note" /> </resultMap> <!-- 拓展resultMap 可以進行繼承操作 --> <resultMap id="userAndPosition1" extends="BaseResultMap" type="TUser"> <association property="position" javaType="TPosition" columnPrefix="post_"> <id column="id" property="id"/> <result column="name" property="postName"/> <result column="note" property="note"/> </association> </resultMap> <!-- 查詢語句 SQL連接查詢 --> <select id="selectUserPosition1" resultMap="userAndPosition1"> select a.id, user_name, real_name, sex, mobile, email, a.note, b.id post_id, b.post_name, b.note post_note from t_user a, t_position b where a.position_id = b.id </select>

XML配置(嵌套條件)

<!-- BaseResultMap -->
<resultMap id="BaseResultMap" type="TUser">
    <id column="id" property="id" />
    <result column="user_name" property="userName" />
    <result column="real_name" property="realName" />
    <result column="sex" property="sex" />
    <result column="mobile" property="mobile" />
    <result column="email" property="email" />
    <result column="note" property="note" />
</resultMap>
<!-- 拓展resultMap 可以進行繼承操作 可以引用其他mapper文件方法-->
<resultMap id="userAndPosition2" extends="BaseResultMap" type="TUser">
    <association property="position" fetchType="lazy"  column="position_id" select="com.enjoylearning.mybatis.mapper.PositionMapper.selectByPrimaryKey" />
    <association property="position2" fetchType="lazy"  column="post_id" select="com.enjoylearning.mybatis.mapper.PositionMapper.selectByPrimaryKey" />
</resultMap>
<!-- 查詢語句 SQL連接查詢  -->
<select id="selectUserPosition2" resultMap="userAndPosition2">
    select
    a.id,
    a.user_name,
    a.real_name,
    a.sex,
    a.mobile,
    a.position_id,
    a.post_id
    from t_user a
</select>

無論是嵌套結果還是嵌套查詢,只要是一對一的關聯都可以用如上方法得到數據。

細心的小夥伴可以發現,在嵌套條件時,我加入了兩個association 分別對應User表中的兩個Position實體,這個用處就在於,當User表關聯兩個Dictionary字典表時,可以進行配置多個也是可以的。

Mybatis 關聯查詢