mybatis的一对多映射
延续mybatis的一对一问题,如果一个用户有多个作品怎么办?这就涉及到了一对多的问题。同样的,mybatis一对多依然可以分为两种方式来解决。
一、使用内嵌的ResultMap实现一对多映射
1)实体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class User implements Serializable{ private static final long serialVersionUID = 112596782083832677L; private Integer id; //编号 private String email; //邮箱 private String realName; //真实姓名 private String telephone; //电话号码 private List<WorksInfo> worksInfos; //作品 //get,set方法 ... } public class WorksInfo implements Serializable{ private Integer id; private Integer userId; private Date uploadDate; //上传时间 private Date updateDate; //更新时间 //get,set方法 ... } |
2)dao接口省略...
3)mapper映射文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
< resultMap type = "com.tarena.djs.entity.WorksInfo" id = "worksInfoResultMap" > < id column = "id" property = "id" /> < result column = "uploadDate" property = "uploadDate" /> < result column = "updateDate" property = "updateDate" /> </ resultMap > < resultMap type = "com.tarena.djs.entity.User" id = "UserResult" > < id column = "id" property = "id" /> < result column = "email" property = "email" /> < result column = "telephone" property = "telephone" /> < result column = "realName" property = "realName" /> < collection property = "worksInfos" resultMap = "worksInfoResultMap" /> </ resultMap > < select id = "findTutorById" parameterType = "int" resultMap = "UserResult" > select u.*,w.* from user u left join worksInfo w on u.id = w.userId where u.id = #{id} </ select > |
4)测试省略
二、嵌套查询方式实现一对多
1)实体类如上
2)dao层接口省略
3)mapper文件映射
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
< resultMap type = "com.tarena.djs.entity.WorksInfo" id = "worksInfoResultMap" > < id column = "id" url = "http://www.errenzhuan.cc" /> < result column = "uploadDate" property = "uploadDate" /> < result column = "updateDate" property = "updateDate" /> </ resultMap > < select id = "findWorksInfoByUserId" parameterType = "int" resultMap = "worksInfoResultMap" > select * from worksInfo where userId = #{userId} </ select > < resultMap type = "com.tarena.djs.entity.User" id = "UserResult" > < id column = "id" property = "id" /> < result column = "email" property = "email" /> < result column = "telephone" property = "telephone" /> < result column = "realName" property = "realName" /> < collection property = "worksInfos" columns = "id" select = "findWorksInfoByUserId" /> </ resultMap > < select id = "findUserByUserId" parameterType = "int" resultMap = "UserResult" > select * from user where id = #{id} </ select > |
4)测试方法忽略
注意:collention元素里的column属性,即主表中要传递给副表做查询的条件,例如本例中:
1
|
< span style = "background-color: rgb(255, 255, 0);" >< collection property = "worksInfos" columns = "id" select = "findWorksInfoByUserId" />< br ></ span > |
及时将user表中的id字段传递给findWorksInfoByUserId方法做参数使用的,对应worksInfo表中的userId字段。除此之外,嵌套select语句会导致N+1的问题。首先,主查询将会执行(1 次) ,对于主
查询返回的每一行,另外一个查询将会被执行(主查询 N 行,则此查询 N 次) 。对于
大型数据库而言,这会导致很差的性能问题。