Mybatis框架(9) —— 实现多表查询操作

简介

多表之间的关系

  • 一对多
    • 用户 ——> 订单、订单、订单、订单
  • 多对一(一对一)
    • 订单、订单、订单、订单 ——> 用户
    • 单个订单 ——> 用户
  • 一对一
    • 中国公民——>身份证
  • 多对多
    • 语文老师、数学老师、英语老师——>小明、小红、小黑、小绿

MyBatis中多表之间的关系

  • 本次案例主要以最为简单的用户(User)、账户(Account)、角色(Role)的模型来分析Mybatis多表关系。
    • 用户为User 表,账户为Account表。
      • 一对多关系
        • 一个用户(User)可以开设多个账户(Account)
          • 从查询 用户信息(User) 出发,关联查询 账户信息(Account)属于一对多查询
      • 一对一关系(多对一)
        • 多个账户(Account)可以对应一个用户(User)
        • 单个账户(Account)只能属于一个用户(User)
          • 从查询 账户信息(Account) 出发,关联查询 用户信息(User)属于一对一查询
      • 多对多关系
        • 一个用户(User)可以拥有多个角色(Role)
        • 一个角色(Role)可以赋予多个用户(User)
          • 多对多关系其实我们看成是双向的一对多关系。

目录结构

  • src
    • main
      • java
        • cn.water.dao
          • M2MDao.java(多对多 持久层接口)
          • O2MDao.java(一对多 持久层接口)
          • O2ODao.java(一对一 持久层接口)
        • cn.water.domain
          • M2M_Role.java(多对多 实体类)
          • M2M_User.java(多对多 实体类)
          • O2M_Account.java(一对多 实体类)
          • O2M_User.java(一对多 实体类)
          • O2O_Account.java(一对一 实体类)
          • O2O_AccountUser.java(一对一 实体类)
          • O2O_User.java(一对一 实体类)
      • resources
        • cn.water.dao
          • M2MDao.xml(多对多 映射配置文件)
          • O2MDao.xml(一对多 映射配置文件)
          • O2ODao.xml(一对一 映射配置文件)
        • SqlMapConfig.xml(MyBatis主配置文件)
        • jdbcConfig.properties(数据库连接信息文件)
    • test
      • java.cn.water
        • MybatisTest.java(测试类)

MyBatis主配置文件

SqlMapConfig.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">


<!-- mybatis的主配置文件 -->
<configuration>

<!-- 外部配置 -->
<properties resource="jdbcConfig.properties"></properties>

<!-- 指定包:实体类-->
<typeAliases>
<package name="cn.water.domain"/>
</typeAliases>

<!-- 配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>

<!-- 指定包:持久层接口 -->
<mappers>
<package name="cn.water.dao"/>
</mappers>

</configuration>

数据库连接信息文件

jdbcConfig.properties

1
2
3
4
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

实体类

M2M_Role.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package cn.water.domain;

import java.io.Serializable;
import java.util.List;

/**
* @author Water
* @date 2019/10/10 - 19:11
* @description ManyToMany 多对多查询
*/
public class M2M_Role implements Serializable {

private Integer roleId;
private String roleName;
private String roleDesc;
private List<M2M_User> users;

@Override
public String toString() {
return "M2M_Role{" +
"roleId=" + roleId +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
", users=" + users +
'}';
}

public Integer getRoleId() {
return roleId;
}

public void setRoleId(Integer roleId) {
this.roleId = roleId;
}

public String getRoleName() {
return roleName;
}

public void setRoleName(String roleName) {
this.roleName = roleName;
}

public String getRoleDesc() {
return roleDesc;
}

public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}

public List<M2M_User> getUsers() {
return users;
}

public void setUsers(List<M2M_User> users) {
this.users = users;
}
}

M2M_User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package cn.water.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
* @author Water
* @date 2019/10/10 - 19:11
* @description ManyToMany 多对多查询
*/
public class M2M_User implements Serializable {

private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
private List<M2M_Role> roles;

@Override
public String toString() {
return "M2M_User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", roles=" + roles +
'}';
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public List<M2M_Role> getRoles() {
return roles;
}

public void setRoles(List<M2M_Role> roles) {
this.roles = roles;
}
}

O2M_Account.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package cn.water.domain;

import java.io.Serializable;

/**
* @author Water
* @date 2019/10/10 - 19:12
* @description OneToMany 一对多查询
*/
public class O2M_Account implements Serializable {

private Integer id;
private Integer uid;
private Double money;


@Override
public String toString() {
return "O2M_Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Integer getUid() {
return uid;
}

public void setUid(Integer uid) {
this.uid = uid;
}

public Double getMoney() {
return money;
}

public void setMoney(Double money) {
this.money = money;
}
}

O2M_User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package cn.water.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
* @author Water
* @date 2019/10/10 - 19:10
* @description OneToMany 一对多查询
*/
public class O2M_User implements Serializable {

private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
private List<O2M_Account> accounts;

@Override
public String toString() {
return "O2M_User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", accounts=" + accounts +
'}';
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public List<O2M_Account> getAccounts() {
return accounts;
}

public void setAccounts(List<O2M_Account> accounts) {
this.accounts = accounts;
}
}

O2O_Account.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package cn.water.domain;

import java.io.Serializable;

/**
* @author Water
* @date 2019/10/10 - 19:12
* @description OneToOne 一对一查询
*/
public class O2O_Account implements Serializable {

private Integer id;
private Integer uid;
private Double money;
private O2O_User user;

@Override
public String toString() {
return "O2O_Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
", user=" + user +
'}';
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Integer getUid() {
return uid;
}

public void setUid(Integer uid) {
this.uid = uid;
}

public Double getMoney() {
return money;
}

public void setMoney(Double money) {
this.money = money;
}

public O2O_User getUser() {
return user;
}

public void setUser(O2O_User user) {
this.user = user;
}
}

O2O_AccountUser.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package cn.water.domain;

import java.io.Serializable;

/**
* @author Water
* @date 2019/10/10 - 19:12
* @description OneToOne 一对一查询
*/
public class O2O_AccountUser extends O2O_Account implements Serializable {

private String username;
private String address;

@Override
public String toString() {
/* 调用父类的toString方法 */
return super.toString()+" O2O_AccountUser{" +
"username='" + username + '\'' +
", address='" + address + '\'' +
'}';
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}
}

O2O_User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package cn.water.domain;

import java.io.Serializable;
import java.util.Date;

/**
* @author Water
* @date 2019/10/10 - 19:10
* @description OneToOne 一对一查询
*/
public class O2O_User implements Serializable {

private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;

@Override
public String toString() {
return "O2O_User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}
}

持久层

M2MDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package cn.water.dao;

import cn.water.domain.M2M_Role;
import cn.water.domain.M2M_User;

import java.util.List;

/**
* @author Water
* @date 2019/10/10 - 19:24
* @description ManyToMany 多对多查询
*/
public interface M2MDao {

/* 多表查询,封装类:Role类 User类 */
List<M2M_Role> findAll01();

/* 多表查询,封装类:Role类 User类 */
List<M2M_User> findAll02();

}

O2MDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package cn.water.dao;

import cn.water.domain.O2M_User;
import cn.water.domain.O2O_Account;
import cn.water.domain.O2O_User;

import java.util.List;

/**
* @author Water
* @date 2019/10/10 - 19:24
* @description OneToMany 一对多查询
*/
public interface O2MDao {

/* 多表查询,封装类:Account类 User类 */
List<O2M_User> findAll ();

}

O2ODao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package cn.water.dao;

import cn.water.domain.O2O_Account;
import cn.water.domain.O2O_AccountUser;

import java.util.List;

/**
* @author Water
* @date 2019/10/10 - 19:24
* @description OneToOne 一对一查询
*/
public interface O2ODao {

/* 多表查询,封装类:Account类 User类*/
List<O2O_Account> findAll01 ();

/* 多表查询,封装类:父类Account 子类AccountUser */
List<O2O_AccountUser> findAll02 ();

}

映射配置文件

M2MDao.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="cn.water.dao.M2MDao">
<!-- 【Role表】 -->
<resultMap id="role" type="m2m_role">
<id property="roleId" column="rid"></id>
<result property="roleName" column="role_name"></result>
<result property="roleDesc" column="role_desc"></result>
<!-- 【User表】 -->
<collection property="users" ofType="m2m_user">
<id column="id" property="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>
</collection>
</resultMap>
<select id="findAll01" resultMap="role">
SELECT
u.*,
r.id rid,
r.role_name,
r.role_desc
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>
</mapper>

O2MDao.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.water.dao.O2MDao">
<!-- 【主表:User】 -->
<resultMap id="o2m" type="o2m_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"/>
<!-- 【次表:Account】 -->
<collection property="accounts" ofType="o2m_account">
<id column="id" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
</collection>
</resultMap>
<!-- 多表查询 -->
<select id="findAll" resultMap="o2m">
SELECT *
FROM user u
LEFT OUTER JOIN account a
ON u.id = a.uid;
</select>
</mapper>

O2ODao.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="cn.water.dao.O2ODao">
<!-- 【次表:Account】 -->
<resultMap id="o2o" type="o2o_account">
<id column="id" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
<!-- 【主表:User】 -->
<association property="user" javaType="o2o_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"/>
</association>
</resultMap>
<!-- 多表查询 -->
<select id="findAll01" resultMap="o2o">
SELECT
u.*,
a.*
FROM
user u,
account a
WHERE
u.id = a.uid;
</select>
<!-- 多表查询 -->
<select id="findAll02" resultType="o2o_accountUser">
SELECT
a.*,
u.username,
u.address
FROM
user u,
account a
WHERE
u.id = a.uid;
</select>
</mapper>

测试类

MyBatisTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package cn.water;

import cn.water.dao.M2MDao;
import cn.water.dao.O2MDao;
import cn.water.dao.O2ODao;
import cn.water.domain.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
* @author Water
* @date 2019/10/10 - 19:44
* @description
*/
public class MybatisTest {

/* 成员变量 */
private InputStream inputStream;
private SqlSession session;

/* 初始化操作 */
@Before
public void init() throws IOException {
/* 加载 MyBatis配置文件 */
inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
/* 获取 工厂类 */
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
/* 获取 产品类 */
session = factory.openSession(true);/* 设置自动提交 */
}

/* 销毁操作 */
@After
public void destroy() throws IOException {
session.close();
inputStream.close();
}

/* OneToOne */
@Test
public void test01(){
O2ODao dao = session.getMapper(O2ODao.class);
for (O2O_Account account : dao.findAll01()) {
System.out.println(account);
}
}

/* OneToOne */
@Test
public void test02(){
O2ODao dao = session.getMapper(O2ODao.class);
for (O2O_AccountUser accountUser : dao.findAll02()) {
System.out.println(accountUser);
}
}

/* OneToMany */
@Test
public void test03(){
O2MDao dao = session.getMapper(O2MDao.class);
for (O2M_User user : dao.findAll()) {
System.out.println(user);
}
}

/* ManyToMany */
@Test
public void test04(){
M2MDao dao = session.getMapper(M2MDao.class);
for (M2M_Role role : dao.findAll01()) {
System.out.println(role);
}
}

/* ManyToMany */
@Test
public void test05(){
M2MDao dao = session.getMapper(M2MDao.class);
for (M2M_User user : dao.findAll02()) {
System.out.println(user);
}
}


}

一对一查询

  • 从查询 账户信息(Account) 出发,关联查询 用户信息(User)

结果集

  • 当我们查询多个表的时候,我们就需要考虑考虑结果集封装类的问题了。
  • 例如,我们需要查询用户(User)的 username字段 和 address字段 以及账户(Account)的 所有字段。
    • 方法一:根据查询方式,将实体类设置为变量。
    • 方法二:根据查询结果,创建新的实体类。

方法一:将实体类设置为变量

  • 在账户类(Account)直接将 用户类(User)设置为变量,于是账户类即封装了账户信息,又封装了用户信息
    • 以持久层接口的方法 find01 为案例,查询 Account.uid 与 User.id 相等的所有 Account信息和 User信息。

用户类

1
2
3
4
5
6
7
8
9
10
11
12
public class O2O_User implements Serializable {

/* 成员变量 */
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;

/* toString方法 省略 */
/* Setter Getter 省略 */
}

账户类(结果集封装类)

  • 将 用户类(User)设置为变量
1
2
3
4
5
6
7
8
9
10
11
12
public class O2O_Account implements Serializable {

/* 成员变量 */
private Integer id;
private Integer uid;
private Double money;
private User user; /* 用户类 */

/* toString方法 省略 */
/* Setter Getter 省略 */

}

持久层接口

1
List<O2O_Account> findAll01 ();

映射配置文件

  • 使用resultMap,定义专门的resultMap用于映射一对一查询结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!-- 【次表:Account】 -->
<resultMap id="o2o" type="o2o_account">
<id column="id" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
<!-- 【主表:User】 -->
<association property="user" javaType="o2o_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"/>
</association>
</resultMap>
<!-- 多表查询 -->
<select id="findAll01" resultMap="o2o">
SELECT
u.*,
a.*
FROM
user u,
account a
WHERE
u.id = a.uid;
</select>

测试类

1
2
3
4
5
6
7
@Test
public void test01(){
O2ODao dao = session.getMapper(O2ODao.class);
for (O2O_Account account : dao.findAll01()) {
System.out.println(account);
}
}

运行结果

1
2
3
4
5
6
7
8
9
10
11
O2O_Account{
id=46,
uid=46,
money=1000.0,
user=O2O_User{id=46, username='老王', birthday=Wed Mar 07 17:37:26 CST 2018, sex='男', address='北京'}}

O2O_Account{
id=45,
uid=45,
money=1000.0,
user=O2O_User{id=45, username='传智播客', birthday=Sun Mar 04 12:04:06 CST 2018, sex='男', address='北京金燕龙'}}

方法二:创建新的实体类

  • 创建 账户子类(AccountUser),由于继承关系我们可以封装账户信息,于是我们只用再设置 usernam变量 和 address变量就可以封装用户信息了。

    • 以持久层接口的方法 find02 为案例,查询 Account.uid 与 User.id 相等的所有 Account信息和 User的usename 和 address信息。

用户类

1
2
3
4
5
6
7
8
9
10
11
12
public class O2O_User implements Serializable {

/* 成员变量 */
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;

/* toString方法 省略 */
/* Setter Getter 省略 */
}

账户类

1
2
3
4
5
6
7
8
9
10
11
public class O2O_Account implements Serializable {

/* 成员变量 */
private Integer id;
private Integer uid;
private Double money;

/* toString方法 省略 */
/* Setter Getter 省略 */

}

账户子类(结果集封装类)

  • 调用父类的toString方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class O2O_AccountUser extends O2O_Account implements Serializable {

/* 成员变量 */
private String username;
private String address;

/* toString方法 省略 */
@Override
public String toString() {
/* 调用父类的toString方法 */
return super.toString()+
" AccountUser{" +
"username='" + username + '\'' +
", address='" + address + '\'' +
'}';
}

/* Setter Getter 省略 */

}

持久层接口

1
List<O2O_AccountUser> findAll02 ();

映射配置文件

1
2
3
4
5
6
7
8
9
10
11
12
 <!-- 多表查询 -->
<select id="findAll02" resultType="o2o_accountUser">
SELECT
a.*,
u.username,
u.address
FROM
user u,
account a
WHERE
u.id = a.uid;
</select>

测试类

1
2
3
4
5
6
7
@Test
public void test02(){
O2ODao dao = session.getMapper(O2ODao.class);
for (O2O_AccountUser accountUser : dao.findAll02()) {
System.out.println(accountUser);
}
}

运行结果

1
2
3
O2O_Account{id=1, uid=46, money=1000.0, user=null}  O2O_AccountUser{username='老王', address='北京'}
O2O_Account{id=2, uid=45, money=1000.0, user=null} O2O_AccountUser{username='传智播客', address='北京金燕龙'}
O2O_Account{id=3, uid=46, money=2000.0, user=null} O2O_AccountUser{username='老王', address='北京'}

一对多查询

  • 从查询 用户信息(User) 出发,关联查询 账户信息(Account)
  • 用户信息和他的账户信息为一对多关系,并且查询过程中如果用户没有账户信息,此时也要将用户信息
    查询出来,我们想到了左外连接查询比较合适。

用户类

  • 一对多关系映射:主表实体类 应该包含 从表实体类的集合引用
1
2
3
4
5
6
7
8
9
10
11
12
13
public class O2M_User implements Serializable {

/* 成员变量 */
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
private List<O2M_Account> accounts;

/* toString方法 省略 */
/* Setter Getter 省略 */
}

账户类

1
2
3
4
5
6
7
8
9
10
11
12
13
public class O2M_Account implements Serializable {

/* 成员变量 */
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
private List<O2M_Account> accounts;

/* toString方法 省略 */
/* Setter Getter 省略 */
}

持久层接口

1
List<O2M_User> findAll ();

映射文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 <!-- 【主表:User】 -->
<resultMap id="o2m" type="o2m_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"/>
<!-- 【次表:Account】 -->
<collection property="accounts" ofType="o2m_account">
<id column="id" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
</collection>
</resultMap>
<!-- 多表查询 -->
<select id="findAll" resultMap="o2m">
SELECT *
FROM
user u
LEFT OUTER JOIN
account a
ON
u.id = a.uid;
</select>

测试类

1
2
3
4
5
6
7
@Test
public void test03(){
O2MDao dao = session.getMapper(O2MDao.class);
for (O2M_User user : dao.findAll()) {
System.out.println(user);
}
}

测试结果

1
2
3
4
5
6
O2M_User{id=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', address='北京', accounts=[O2M_Account{id=41, uid=null, money=null}]}
O2M_User{id=42, username='小二王', birthday=Fri Mar 02 15:09:37 CST 2018, sex='女', address='北京金燕龙', accounts=[O2M_Account{id=42, uid=null, money=null}]}
O2M_User{id=43, username='小二王', birthday=Sun Mar 04 11:34:34 CST 2018, sex='女', address='北京金燕龙', accounts=[O2M_Account{id=43, uid=null, money=null}]}
O2M_User{id=45, username='传智播客', birthday=Sun Mar 04 12:04:06 CST 2018, sex='男', address='北京金燕龙', accounts=[O2M_Account{id=45, uid=45, money=1000.0}]}
O2M_User{id=46, username='老王', birthday=Wed Mar 07 17:37:26 CST 2018, sex='男', address='北京', accounts=[O2M_Account{id=46, uid=46, money=1000.0}]}
O2M_User{id=48, username='小马宝莉', birthday=Thu Mar 08 11:44:00 CST 2018, sex='女', address='北京修正', accounts=[O2M_Account{id=48, uid=null, money=null}]}

多对多查询

  • 多对多关系其实我们看成是双向的一对多关系。

用户类

  • 多对多关系映射:两个实体类应该包含彼此的集合引用
1
2
3
4
5
6
7
8
9
10
11
12
13
public class M2M_User implements Serializable {

/* 成员变量 */
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
private List<M2M_Role> roles;

/* toString方法 省略 */
/* Setter Getter 省略 */
}

角色类

  • 多对多关系映射:两个实体类应该包含彼此的集合引用
1
2
3
4
5
6
7
8
9
10
11
public class M2M_Role implements Serializable {

/* 成员变量 */
private Integer roleId;
private String roleName;
private String roleDesc;
private List<M2M_User> users;

/* toString方法 省略 */
/* Setter Getter 省略 */
}

持久层接口

1
List<M2M_Role> findAll();

映射文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 <!-- 【Role表】 -->
<resultMap id="role" type="m2m_role">
<id property="roleId" column="rid"></id>
<result property="roleName" column="role_name"></result>
<result property="roleDesc" column="role_desc"></result>
<!-- 【User表】 -->
<collection property="users" ofType="m2m_user">
<id column="id" property="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>
</collection>
</resultMap>
<select id="findAll" resultMap="role">
SELECT
u.*,
r.id rid,
r.role_name,
r.role_desc
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>

测试类

1
2
3
4
5
6
7
@Test
public void test04(){
M2MDao dao = session.getMapper(M2MDao.class);
for (M2M_Role role : dao.findAll()) {
System.out.println(role);
}
}

测试结果

1
2
3
M2M_Role{roleId=1, roleName='院长', roleDesc='管理整个学院', users=[M2M_User{id=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', address='北京', roles=null}, M2M_User{id=45, username='传智播客', birthday=Sun Mar 04 12:04:06 CST 2018, sex='男', address='北京金燕龙', roles=null}]}
M2M_Role{roleId=2, roleName='总裁', roleDesc='管理整个公司', users=[M2M_User{id=41, username='老王', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', address='北京', roles=null}]}
M2M_Role{roleId=3, roleName='校长', roleDesc='管理整个学校', users=[]}

比较:O2O O2M

一对一

实体类

  • 用户类

    • id
    • username
    • birthday
    • sex
    • address
  • 账户类

    • id
    • uid
    • money
    • user

映射配置文件

  • association标签
    • javaType属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- 【次表:Account】 -->
<resultMap id="accountUserMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!-- 【主表:User】 -->
<association property="user" 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>

一对多

实体类

  • 用户类

    • id
    • username
    • birthday
    • sex
    • address
    • LIst<Account>
  • 账户类

    • id
    • uid
    • money

映射配置文件

  • collection标签
    • ofType属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- 【主表:User】 -->
<resultMap id="userAccountMap" type="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>
<!-- 【次表:Account】 -->
<collection property="accounts" ofType="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
</collection>
</resultMap>
-------------本文结束-------------
Donate comment here