
Mybatis 的多表关联查询

3.1 一对一查询
- SELECT
- account.*,
- user.username,
- user.address
- FROM
- account,
- user
- WHERE account.uid = user.id
3.1.1.3 定义 AccountCustomer 类

3.1.1.4 定义 AccountDao 接口
3.1.1.5 定义 AccountDao.xml 文件中的查询配置信息

3.1.1.6 创建 AccountTest 测试类
编写 AccountTest 测试类,用于测试查询结果。

3.1.2.2 修改 AccountDao 接口中的方法

3.1.2.3 重写 Account 类的 toString()方法

3.1.2.4 重新定义 AccountDao.xml 文件
3.1.2.5 在 AccountTest 类中加入测试方法

3.2 一对多查询
- SELECT
- u.*, acc.id id,
- acc.uid,
- acc.money
- FROM
- user u
- LEFT JOIN account acc ON u.id = acc.uid
3.2.2 改写 User 类加入 List
3.2.3 UserDao 接口中加入查询方法
在 UserDao 接口中加入查询方法:public List

3.2.4 修改 UserDao.xml 映射文件


Account 类的 toString()方法
3.3 Mybatis 维护多对多关系
用户角色中间表

3.3.1.2 业务要求及实现 SQL
- SELECT
- r.*,u.id uid,
- u.username username,
- u.birthday birthday,
- u.sex sex,
- u.address address
- FROM
- ROLE r
- INNER JOIN
- USER_ROLE ur
- ON ( r.id = ur.rid)
- INNER JOIN
- USER u
- ON (ur.uid = u.id);
其中 Role 类中 userList 集合就是用于存在该角色分配给的用户列表。
3.3.1.4 编写 RoleDao 接口
3.3.1.5 编写 RoleDao.xml 映射文件
第二步:在 RoleDao.xml 文件中加入 SQL 语句的映射



注意:为了显示效果,需要重载 Role 类的 toString()方法

3.3.2 实现 User 到 Role 的多对多