1.关系映射,主表实体应该包含从表实体的集合引用
User表内(User为主表)
private List<Account> accounts;
public List<Account> getAccounts() { return accounts; }
public void setAccounts(List<Account> accounts) { this.accounts = accounts; }
Account表内(Account为主表)
private User user;
public User getUser() { return user;}
public void setUser(User user) { this.user = user; }
2.定义封装account和user的resultMap
<resultMap id="accountUserMap" type="account">
<id property="id" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!-- 一对一的关系映射,配置封装user的内容-->
<association property="user" column="uid" javaType="user">
<id property="id" column="id"></id>
<result column="username" property="username"></result>
<result column="address" property="address"></result>
<result column="sex" property="sex"></result>
<result column="birthday" property="birthday"></result>
</association>
</resultMap>
<!-- 定义User的resultMap-->
<resultMap id="userAccountMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<!-- 配置user对象中accounts集合的映射-->
<collection property="accounts" ofType="account">
<id column="id" property="id"></id>
<result column="uid" property="uid"></result>
<result column="money" property="money"></result>
</collection>
</resultMap>
3.查询示例
<select id="findAll" resultMap="roleMap">
SELECT u.*,r.id AS rid,r.`ROLE_DESC`,r.`ROLE_NAME` FROM role r
LEFT OUTER JOIN user_role ur ON r.id=ur.rid
LEFT OUTER JOIN USER u ON u.id=ur.uid
</select>