前面幾篇博客我們用mybatis能對單表進行增刪改查操作了,也能用動態SQL書寫比較復雜的sql語句。但是在實際開發中,我們做項目不可能只是單表操作,往往會涉及到多張表之間的關聯操作。那么我們如何用 mybatis 處理多表之間的關聯操作呢?請看本篇博客詳解。
本篇詳細代碼:http://pan.baidu.com/s/1eSzmst8 密碼:3n3o
1、一對一
我們以用戶表 user 和訂單表 orders 為例。設定一個訂單只能由一個 用戶創建,那么由訂單到用戶就是一對一的關系。
①、創建用戶表 user 和訂單表 orders
用戶表 user

訂單表 orders

②、創建項目工程,導入相應的 jar 包

③、創建實體類

User.java
package com.ys.po;
public class User {
//用戶ID
private int id;
//用戶姓名
private String username;
//用戶性別
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ "]";
}
}
Orders.java
package com.ys.po;
public class Orders {
//訂單ID
private int id;
//用戶ID
private int userId;
//訂單數量
private String number;
//和用戶表構成一對一的關系,即一個訂單只能由一個用戶創建
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Orders [id=" + id + ", userId=" + userId + ", number=" + number
+ ", user=" + user + "]";
}
}
④、創建 OrderMapper 接口和 OrderMapper.xml 文件

由於我們采用 Mapper 代理加載 xxxMapper.xml 文件,這里我們重復一下 Mapper 代理所需的條件,接口和xml文件必須滿足以下幾個條件:
1、接口必須要和 xml 文件同名且在同一個包下,也就是說 xml 文件中的namespace是接口的全類名
2、接口中的方法名和xml 文件中定義的 id 一致
3、接口輸入參數類型要和xml 中定義的 parameterType 一致
4、接口返回數據類型要和xml 中定義的 resultType 一致
詳細介紹參考上一篇博客:http://www.cnblogs.com/ysocean/p/7301548.html
OrderMapper 接口
package one.to.one.mapper;
import com.ys.po.Orders;
import com.ys.po.User;
public interface OrdersMapper {
/**
* 方式一:嵌套結果
* select * from orders o,user u where o.user_id=u.id and o.id=#{id}
* @param orderId
* @return
*/
//根據訂單ID查詢訂單和用戶信息
public Orders selectOrderAndUserByOrderID(int orderId);
/**
* 方式二:嵌套查詢
* select * from order WHERE id=1;//得到user_id
* select * from user WHERE id=1 //1 是上一個查詢得到的user_id的值
* @param userID
* @return
*/
//根據訂單ID得到訂單信息(包含user_id)
public Orders getOrderByOrderId(int orderId);
//根據用戶ID查詢用戶信息
public User getUserByUserId(int userID);
}
OrderMapper .xml文件
<?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="one.to.one.mapper.OrdersMapper">
<!--
嵌套結果:使用嵌套結果映射來處理重復的聯合結果的子集
封裝聯表查詢的數據(去除重復的數據)
select * from orders o,user u where o.user_id=u.id and o.id=#{id}
-->
<select id="selectOrderAndUserByOrderID" resultMap="getOrderAndUser">
select * from orders o,user u where o.user_id=u.id and o.id=#{id}
</select>
<resultMap type="com.ys.po.Orders" id="getOrderAndUser">
<!--
id:指定查詢列表唯一標識,如果有多個唯一標識,則配置多個id
column:數據庫對應的列
property:實體類對應的屬性名
-->
<id column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<!--association:用於映射關聯查詢單個對象的信息
property:實體類對應的屬性名
javaType:實體類對應的全類名
-->
<association property="user" javaType="com.ys.po.User">
<!--
id:指定查詢列表唯一標識,如果有多個唯一標識,則配置多個id
column:數據庫對應的列
property:實體類對應的屬性名
-->
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
</association>
</resultMap>
<!--
方式二:嵌套查詢:通過執行另外一個SQL映射語句來返回預期的復雜類型
select user_id from order WHERE id=1;//得到user_id
select * from user WHERE id=1 //1 是上一個查詢得到的user_id的值
property:別名(屬性名) column:列名 -->
<select id="getOrderByOrderId" resultMap="getOrderMap">
select * from order where id=#{id}
</select>
<resultMap type="com.ys.po.Orders" id="getOrderMap">
<id column="id" property="id"/>
<result column="number" property="number"/>
<association property="userId" column="id" select="getUserByUserId">
</association>
</resultMap>
<select id="getUserByUserId" resultType="com.ys.po.User">
select * from user where id=#{id}
</select>
</mapper>
⑤、向 mybatis-configuration.xml 配置文件中注冊 OrderMapper.xml 文件
<?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">
<configuration>
<!-- 加載數據庫屬性文件 -->
<properties resource="db.properties"></properties>
<!-- 定義別名 -->
<typeAliases>
<!-- mybatis自動掃描包中的po類,自動定義別名,別名是類名(首字母大寫或小寫都可以,一般用小寫) -->
<package name="com.ys.po"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!--dataSource 元素使用標准的 JDBC 數據源接口來配置 JDBC 連接對象源 -->
<dataSource type="POOLED">
<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>
<!-- 通過OrdersMapper接口注冊OrdersMapper.xml文件,
必須保證:接口和xml在同一個包下,而且名字一樣
OrdersMapper接口的方法名和OrdersMapper.xml文件的id一樣
OrdersMapper接口的輸出輸出參數和OrdersMapper.xml文件resultType,parameterType類型一樣
-->
<mapper class="one.to.one.mapper.OrdersMapper"/>
</mappers>
</configuration>
⑥、測試
package one.to.one.mapper;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.ys.po.Orders;
public class OneToOneTest {
//定義 SqlSession
SqlSession session =null;
@Before
public void init(){
//定義mybatis全局配置文件
String resource = "mybatis-configuration.xml";
//加載 mybatis 全局配置文件
InputStream inputStream = OneToOneTest.class.getClassLoader()
.getResourceAsStream(resource);
//構建sqlSession的工廠
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//根據 sqlSessionFactory 產生 session
session = sessionFactory.openSession();
}
/**
* 方式一:嵌套結果
* select * from orders o,user u where o.user_id=u.id and o.id=#{id}
*/
@Test
public void testSelectOrderAndUserByOrderId(){
String statement = "one.to.one.mapper.OrdersMapper.selectOrderAndUserByOrderID";
//創建OrdersMapper對象,mybatis自動生成mapepr代理對象
OrdersMapper orderMapper = session.getMapper(OrdersMapper.class);
Orders order = orderMapper.selectOrderAndUserByOrderID(1);
System.out.println(order);
session.close();
}
/**
* 方式二:嵌套查詢
* select * from order WHERE id=1;//得到user_id
* select * from user WHERE id=1 //1 是上一個查詢得到的user_id的值
*/
@Test
public void testgetOrderByOrderId(){
String statement = "one.to.one.mapper.OrdersMapper.getOrderByOrderId";
//創建OrdersMapper對象,mybatis自動生成mapepr代理對象
OrdersMapper orderMapper = session.getMapper(OrdersMapper.class);
Orders order = orderMapper.selectOrderAndUserByOrderID(1);
System.out.println(order);
session.close();
}
}
2、一對多
還是以用戶表 user 和 訂單表 orders 為例,一個用戶能創建多個訂單。故用戶和訂單構成一對多的關聯。
我們在 user.java 中添加一個屬性 public List<Orders> orders;
①、創建實體類
user.java如下,orders.java保持不變
package com.ys.po;
import java.util.List;
public class User {
//用戶ID
private int id;
//用戶姓名
private String username;
//用戶性別
private String sex;
//一個用戶能創建多個訂單,用戶和訂單構成一對多的關系
public List<Orders> orders;
public List<Orders> getOrders() {
return orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ "]";
}
}
②、創建 UserMapper 接口和 UserMapper.xml 文件

UserMapper接口
package one.to.many.mapper;
import com.ys.po.User;
public interface UserMapper {
//根據用戶id查詢用戶信息,以及用戶下面的所有訂單信息
public User selectUserAndOrdersByUserId(int UserId);
}
UserMapper.xml
<?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="one.to.many.mapper.UserMapper">
<!--
方式一:嵌套結果:使用嵌套結果映射來處理重復的聯合結果的子集
封裝聯表查詢的數據(去除重復的數據)
select * from user u,orders o where u.id=o.user_id and u.id=#{id}
-->
<select id="selectUserAndOrdersByUserId" resultMap="getUserAndOrders">
select u.*,o.id oid,o.number number from user u,orders o where u.id=o.user_id and u.id=#{id}
</select>
<resultMap type="com.ys.po.User" id="getUserAndOrders">
<!--id:指定查詢列表唯一標識,如果有多個唯一標識,則配置多個id
column:數據庫對應的列
property:實體類對應的屬性名 -->
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<!--
property:實體類中定義的屬性名
ofType:指定映射到集合中的全類名
-->
<collection property="orders" ofType="com.ys.po.Orders">
<id column="oid" property="id"/>
<result column="number" property="number"/>
</collection>
</resultMap>
</mapper>
③、向 mybatis-configuration.xml 配置文件中注冊 UserMapper.xml 文件

④、測試
@Test
public void testSelectOrderAndUserByOrderId(){
String statement = "one.to.many.mapper.UserMapper.selectUserAndOrdersByUserId";
//創建OrdersMapper對象,mybatis自動生成mapepr代理對象
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.selectUserAndOrdersByUserId(1);
System.out.println(user.getOrders().size());
session.close();
}
3、多對多
這里我們以用戶 user 表和 角色role 表為例,假定一個用戶能被分配成多重角色,而一種角色也能分給多個用戶,故用戶和角色構成多對多的關系。
需求:給定角色id,查詢這個角色所屬的所有用戶信息
①、在數據庫中建立相應的表
user 表和上面的保持不變
role 表

兩者之間的關聯表user_role

②、建立對應的實體類
User.java

Role.java
package com.ys.po;
import java.util.List;
public class Role {
private int id;
private String name;
private List<User> users;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
User_Role.java
package com.ys.po;
public class User_Role {
private User user;
private Role role;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
③、創建 UserMapper 接口和 UserMapper.xml 文件
UserMapper 接口
package many.to.many.mapper;
import java.util.List;
import com.ys.po.User;
public interface UserMapper {
//給定一個角色id,要得到具有這個角色的所有用戶信息
public List<User> getUserByRoleId(int roleId);
}
UserMapper.xml
<?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="many.to.many.mapper.UserMapper">
<select id="getUserByRoleId" resultMap="getUserMap">
select * from user_role ur,user u where ur.user_id=u.id and ur.role_id=#{id}
</select>
<resultMap type="com.ys.po.User" id="getUserMap">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
</resultMap>
</mapper>
④、向 mybatis-configuration.xml 配置文件中注冊 UserMapper.xml 文件

⑤、測試
@Test
public void testGetUserByRoleId(){
String statement = "many.to.many.mapper.UserMapper.getUserByRoleId";
//創建OrdersMapper對象,mybatis自動生成mapepr代理對象
UserMapper userMapper = session.getMapper(UserMapper.class);
List<User> users = userMapper.getUserByRoleId(1);
session.close();
}
多對多主要是關聯關系要找好,然后根據關聯去查詢。
