1.一对一映射(association实现方案)
1.1.java类
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
// getter/setter方法...(省略)
}
public class Account {
private Integer id;
private Integer uid;
private Double money;
// 高级映射:一对一映射(association实现方案)
private User user;
// getter/setter方法...(省略)
}
1.2.xml写法
<!--
1.高级映射:一对一映射(association实现方案),一对多映射(collection实现方案)
-->
<resultMap id="AccountMapAssociation" type="Account">
<id column="id" property="id"/>
<result column="money" property="money"/>
<result column="uid" property="uid"/>
<association property="user" javaType="User">
<id column="userid" property="id"/>
<result column="username" property="username"/>
<result column="birthday" property="birthday"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
</association>
</resultMap>
<select id="findAccoutnByAid" resultMap="AccountMapAssociation">
SELECT u.id userid , u.username , u.sex , u.birthday , u.address ,a.*
FROM user u, account a
WHERE
u.id=a.uid and a.id = #{id}
</select>
2.一对多映射(collection实现方案)
2.1.java类
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
//用户封装用户的账户信息
private List<Account> accountList;
// getter/setter方法...(省略)
}
public class Account {
private Integer id;
private Integer uid;
private Double money;
// getter/setter方法...(省略)
}
2.2.xml
<!--
2.高级映射:一对多映射(collection实现方案)
-->
<resultMap id="UserResultMap" type="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="birthday" property="birthday"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
<collection property="accountList" ofType="Account">
<id column="aid" property="id"/>
<result column="money" property="money"/>
<result column="uid" property="uid"/>
</collection>
</resultMap>
<select id="findUser" resultMap="UserResultMap">
SELECT u.*, a.id aid,a.uid, a.money
FROM user u , account a
WHERE u.id = a.uid and u.id = #{id}
</select>