多对一 :
SqlMapConfig.xml
<!--typeAliases标签用于起别名,这样package指定包中的实体类的类名可以在Mapper.xml的resultType中直接使用,无需写全限定类名-->
<typeAliases>
<package name="com.company.domain"/>
</typeAliases><environments default="mysql">
...</environments>
实体类
public class Account {
private Integer id;
private Integer uid;
private Double money;
/**
* 多对一实体属性
*/
private User user;
setter和getter省略。。。
}
Mapper映射文件
<resultMap id="accountMap" type="Account">
<id property="id" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result><!--配置多对一实体属性,javaType属性如果未在配置文件中取别名,则需写全限定类名--><association property="user" javaType="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
</association>
</resultMap>
<select id="findAll" resultMap="accountMap">SELECT
a.id aid,
a.uid,
a.money,
u.*
FROM
USER u
RIGHT JOIN account a ON u.id = a.uid;</select>
一对多 :
实体类
public class User {
private Integer id;
private String username;
private Date birthday;
private Character sex;
private String address;
private List<Account> accounts;
setter和getter省略。。。
}
Mapper映射文件
<resultMap id="userMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
<!--配置一对多属性-->
<collection property="accounts" ofType="Account">
<id property="id" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="userMap">
SELECT
u.*,
a.id aid,
a.uid,
a.money
FROM
USER u
LEFT JOIN account a ON u.id = a.uid;
</select>
多对多 :
实体类
public class User {
private Integer id;
private String username;
private Date birthday;
private Character sex;
private String address;
private List<Account> accounts;
private List<Role> roles;
}
Mapper映射文件
<resultMap id="userMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="birthday" column="birthday"></result>
<result property="sex" column="sex"></result>
<result property="address" column="address"></result>
<!--配置一对多属性,在role的dao中反向也一对多,即完成了多对多-->
<collection property="accounts" ofType="Account">
<id property="id" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
</collection>
</resultMap><select id="findRoleAll" resultMap="roleMap">
SELECT
u.*,
r.id rid,
r.role_desc,
r.role_name
FROM
USER u
LEFT JOIN user_role ur ON u.id = ur.uid
LEFT JOIN role r ON ur.rid = r.id;
</select>