1. 程式人生 > 其它 >11.關聯(級聯)查詢

11.關聯(級聯)查詢

一、MyBatis一對一關聯查詢

一對一級聯關係在現實生活中是十分常見的,例如一個大學生只有一個學號,一個學號只屬於一個學生。同樣,人與身份證也是一對一的級聯關係。

在 MyBatis 中,通過 <resultMap> 元素的子元素 <association> 處理一對一級聯關係。示例程式碼如下。

  • <association property="studentCard" column="cardId"
  • javaType="net.biancheng.po.StudentCard"
  • select="net.biancheng.mapper.StudentCardMapper.selectStuCardById"
    />

在 <association> 元素中通常使用以下屬性。

  • property:指定對映到實體類的物件屬性。
  • column:指定表中對應的欄位(即查詢返回的列名)。
  • javaType:指定對映到實體物件屬性的型別。
  • select:指定引入巢狀查詢的子 SQL 語句,該屬性用於關聯對映中的巢狀查詢。


一對一關聯查詢可採用以下兩種方式:

  • 單步查詢,通過關聯查詢實現
  • 分步查詢,通過兩次或多次查詢,為一對一關係的實體 Bean 賦值

1.1 示例

下面以學生和學號為例講解一對一關聯查詢的處理過程。

1)建立資料表

建立 student(學生)和 studentcard(學號)資料表,SQL 語句如下。

CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`sex` tinyint(4) DEFAULT NULL,
`cardId` int(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `cardId` (`cardId`),
CONSTRAINT `student_ibfk_1` FOREIGN KEY (`cardId`) REFERENCES `studentcard` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;


insert into `student`(`id`,`name`,`sex`,`cardId`) values (1,'C語言中文網',0,1),(2,'程式設計幫',0,2),(3,'趙小紅',1,3),(4,'李曉明',0,4),(5,'李紫薇',1,5),(6,'錢百百',0,NULL);


DROP TABLE IF EXISTS `studentcard`;


CREATE TABLE `studentcard` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`studentId` int(20) DEFAULT NULL,
`startDate` date DEFAULT NULL,
`endDate` date DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `studentId` (`studentId`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;


insert into `studentcard`(`id`,`studentId`,`startDate`,`endDate`) values (1,20200311,'2021-03-01','2021-03-11'),(2,20200314,'2021-03-01','2021-03-11'),(3,20200709,'2021-03-01','2021-03-11'),(4,20200508,'2021-03-01','2021-03-11'),(5,20207820,'2021-03-01','2021-03-11');

2)建立持久化類

在 myBatisDemo 應用的 net.biancheng.po 包下建立資料表對應的持久化類 Student 和 StudentCard。

Student 的程式碼如下:

package net.biancheng.po;


public class Student {
private int id;
private String name;
private int sex;


private StudentCard studentCard;


/*省略setter和getter方法*/


@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", studentCard=" + studentCard + "]";
}
}

StudentCard 的程式碼如下:

package net.biancheng.po;


import java.util.Date;


public class StudentCard {
private int id;
private int studentId;
private Date startDate;
private Date endDate;


/*省略setter和getter方法*/


@Override
public String toString() {
return "StudentCard [id=" + id + ", studentId=" + studentId + "]";
}
}

1.2 分步查詢

新建 StudentCardMapper 類,程式碼如下。

package net.biancheng.mapper;
import net.biancheng.po.StudentCard;


public interface StudentCardMapper {
public StudentCard selectStuCardById(int id);
}

StudentCardMapper.xml 對應對映 SQL 語句程式碼如下。

<mapper namespace="net.biancheng.mapper.StudentCardMapper">
<select id="selectStuCardById"
resultType="net.biancheng.po.StudentCard">
SELECT * FROM studentCard WHERE id = #{id}
</select>
</mapper>

StudentMapper 類方法程式碼如下。

package net.biancheng.mapper;
import net.biancheng.po.Student;


public interface StudentMapper {
public Student selectStuById1(int id);
public Student selectStuById2(int id);
}

StudentMapper.xml 程式碼如下。

<mapper namespace="net.biancheng.mapper.StudentMapper">
<!-- 一對一根據id查詢學生資訊:級聯查詢的第一種方法(巢狀查詢,執行兩個SQL語句) -->
<resultMap type="net.biancheng.po.Student" id="cardAndStu1">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="sex" column="sex" />
<!-- 一對一級聯查詢 -->
<association property="studentCard" column="cardId"
javaType="net.biancheng.po.StudentCard"
select="net.biancheng.mapper.StudentCardMapper.selectStuCardById" />
</resultMap>
<select id="selectStuById1" parameterType="Integer"
resultMap="cardAndStu1">
select * from student where id=#{id}
</select>
</mapper>

測試程式碼如下。

public class Test {
public static void main(String[] args) throws IOException {
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
SqlSession ss = ssf.openSession();


Student stu = ss.getMapper(StudentMapper.class).selectStuById1(2);
System.out.println(stu);
}
}

執行結果如下。

DEBUG [main] - ==>  Preparing: select * from student where id=?
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - ====>  Preparing: SELECT * FROM studentCard WHERE id = ?
DEBUG [main] - ====> Parameters: 2(Integer)
DEBUG [main] - <====      Total: 1
DEBUG [main] - <==      Total: 1
Student [id=2, name=程式設計幫, sex=0, studentCard=StudentCard [id=2, studentId=20200314]]

2.單步查詢

在 StudentMapper.xml 中新增以下程式碼。

<resultMap type="net.biancheng.po.Student" id="cardAndStu2">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="sex" column="sex" />
<!-- 一對一級聯查詢 -->
<association property="studentCard"
javaType="net.biancheng.po.StudentCard">
<id property="id" column="id" />
<result property="studentId" column="studentId" />
</association>
</resultMap>
<select id="selectStuById2" parameterType="Integer"
resultMap="cardAndStu2">
SELECT s.*,sc.studentId FROM student s,studentCard sc
WHERE
s.cardId = sc.id AND s.id=#{id}
</select>

在 StudentMapper 中新增以下方法。

  • public Student selectStuById2(int id);

執行結果如下。

DEBUG [main] - ==>  Preparing: SELECT s.*,sc.studentId FROM student s,studentCard sc WHERE s.cardId = sc.id AND s.id=?
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <==      Total: 1
Student [id=2, name=程式設計幫, sex=0, studentCard=StudentCard [id=2, studentId=20200314]]

二、一對多關聯查詢

在實際生活中也有許多一對多級聯關係,例如一個使用者可以有多個訂單,而一個訂單隻屬於一個使用者。同樣,國家和城市也屬於一對多級聯關係。

在 MyBatis 中,通過 <resultMap> 元素的子元素 <collection> 處理一對多級聯關係,collection 可以將關聯查詢的多條記錄對映到一個 list 集合屬性中。示例程式碼如下。
  • <collection property="orderList"
  • ofType="net.biancheng.po.Order" column="id"
  • select="net.biancheng.mapper.OrderMapper.selectOrderById" />
在 <collection> 元素中通常使用以下屬性。
  • property:指定對映到實體類的物件屬性。
  • column:指定表中對應的欄位(即查詢返回的列名)。
  • javaType:指定對映到實體物件屬性的型別。
  • select:指定引入巢狀查詢的子 SQL 語句,該屬性用於關聯對映中的巢狀查詢。

一對多關聯查詢可採用以下兩種方式:
  • 分步查詢,通過兩次或多次查詢,為一對多關係的實體 Bean 賦值
  • 單步查詢,通過關聯查詢實現

2.1 示例

下面以使用者和訂單為例講解一對多關聯查詢(實現“根據 id 查詢使用者及其關聯的訂單資訊”的功能)的處理過程。

1)建立資料表

本例項需要兩張資料表,一張是使用者表 user,一張是訂單表 order,這兩張表具有一對多的級聯關係。SQL 語句如下:
CREATE TABLE `order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ordernum` int(25) DEFAULT NULL,
`userId` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `userId` (`userId`),
CONSTRAINT `order_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;


insert into `order`(`id`,`ordernum`,`userId`) values (1,20200107,1),(2,20200806,2),(3,20206702,3),(4,20200645,1),(5,20200711,2),(6,20200811,2),(7,20201422,3),(8,20201688,4);


DROP TABLE IF EXISTS `user`;


CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`pwd` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;


insert into `user`(`id`,`name`,`pwd`) values (1,'程式設計幫','123'),(2,'C語言中文網','456'),(3,'趙小紅','123'),(4,'李曉明','345'),(5,'楊小胤','123'),(6,'谷小樂','789');

2)建立持久化類

建立持久化類 User 和 Order,程式碼分別如下。
package net.biancheng.po;


import java.util.List;


public class User {
private int id;
private String name;
private String pwd;
private List<Order> orderList;


/*省略setter和getter方法*/


@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", orderList=" + orderList + "]";
}
}
Order 類程式碼如下。
package net.biancheng.po;


public class Order {
private int id;
private int ordernum;


/*省略setter和getter方法*/


@Override
public String toString() {
return "Order [id=" + id + ", ordernum=" + ordernum + "]";
}
}

2.2 分步查詢

OrderMapper 類程式碼如下。
  • public List<Order> selectOrderById(int id);
OrderMapper.xml 中相應的對映 SQL 語句如下。
  • <!-- 根據id查詢訂單資訊 -->
  • <select id="selectOrderById" resultType="net.biancheng.po.Order"
  • parameterType="Integer">
  • SELECT * FROM `order` where userId=#{id}
  • </select>
UserMapper 類程式碼如下。
  • public User selectUserOrderById1(int id);
UserMapper.xml 中相應的對映 SQL 語句如下。
<!-- 一對多 根據id查詢使用者及其關聯的訂單資訊:級聯查詢的第一種方法(分步查詢) -->
<resultMap type="net.biancheng.po.User" id="userAndOrder1">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="pwd" column="pwd" />
<!-- 一對多級聯查詢,ofType表示集合中的元素型別,將id傳遞給selectOrderById -->
<collection property="orderList"
ofType="net.biancheng.po.Order" column="id"
select="net.biancheng.mapper.OrderMapper.selectOrderById" />
</resultMap>
<select id="selectUserOrderById1" parameterType="Integer"
resultMap="userAndOrder1">
select * from user where id=#{id}
</select>
測試程式碼如下。
public class Test {
public static void main(String[] args) throws IOException {
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
SqlSession ss = ssf.openSession();


User us = ss.getMapper(UserMapper.class).selectUserOrderById1(1);
System.out.println(us);
}
}
執行結果如下。
DEBUG [main] - ==>  Preparing: select * from user where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - ====>  Preparing: SELECT * FROM `order` where userId=?
DEBUG [main] - ====> Parameters: 1(Integer)
DEBUG [main] - <====      Total: 2
DEBUG [main] - <==      Total: 1
User [id=1, name=程式設計幫, orderList=[Order [id=0, ordernum=20200107], Order [id=0, ordernum=20200645]]]

2.3單步查詢

該種方式實現一對多關聯查詢需要修改 Order 持久化類,因為 Order 中的 id 不能和 User 中的 id 重複。
package net.biancheng.po;


public class Order {
private int oId;
private int ordernum;


/*省略setter和getter方法*/


@Override
public String toString() {
return "Order [id=" + oId+ ", ordernum=" + ordernum + "]";
}
}
UserMapper 類程式碼如下。
  • public User selectUserOrderById2(int id);
UserMapper.xml 中相關對映 SQL 語句如下。
<!-- 一對多 根據id查詢使用者及其關聯的訂單資訊:級聯查詢的第二種方法(單步查詢) -->
<resultMap type="net.biancheng.po.User" id="userAndOrder2">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="pwd" column="pwd" />
<!-- 一對多級聯查詢,ofType表示集合中的元素型別 -->
<collection property="orderList"
ofType="net.biancheng.po.Order">
<id property="oId" column="oId" />
<result property="ordernum" column="ordernum" />
</collection>
</resultMap>
<select id="selectUserOrderById2" parameterType="Integer"
resultMap="userAndOrder2">
SELECT u.*,o.id as oId,o.ordernum FROM `user` u,`order` o
WHERE
u.id=o.`userId` AND u.id=#{id}
</select>
測試程式碼修改呼叫方法,如下。
public class Test {
public static void main(String[] args) throws IOException {
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
SqlSession ss = ssf.openSession();


User us = ss.getMapper(UserMapper.class).selectUserOrderById2(1);
System.out.println(us);
}
}
執行結果如下。
DEBUG [main] - ==>  Preparing: SELECT u.*,o.id as oId,o.ordernum FROM `user` u,`order` o WHERE u.id=o.`userId` AND u.id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 2
User [id=1, name=程式設計幫, orderList=[Order [id=1, ordernum=20200107], Order [id=4, ordernum=20200645]]]

三、MyBatis多對多關聯查詢

實際應用中,由於多對多的關係比較複雜,會增加理解和關聯的複雜度,所以應用較少。MyBatis 沒有實現多對多級聯,推薦通過兩個一對多級聯替換多對多級聯,以降低關係的複雜度,簡化程式。

例如,一個訂單可以有多種商品,一種商品可以對應多個訂單,訂單與商品就是多對多的級聯關係。可以使用一箇中間表(訂單記錄表)將多對多級聯轉換成兩個一對多的關係。

3.1 示例

下面以訂單和商品(實現“查詢所有訂單以及每個訂單對應的商品資訊”的功能)為例講解多對多關聯查詢。

1. 建立資料表

建立 order(訂單),product(商品)和 order_details(訂單和商品中間表),SQL 語句如下。

CREATE TABLE `order` (
`oid` int(11) NOT NULL AUTO_INCREMENT,
`ordernum` int(25) DEFAULT NULL,
`userId` int(11) DEFAULT NULL,
PRIMARY KEY (`oid`),
KEY `userId` (`userId`),
CONSTRAINT `order_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;


insert into `order`(`oid`,`ordernum`,`userId`) values (1,20200107,1),(2,20200806,2),(3,20206702,3),(4,20200645,1),(5,20200711,2),(6,20200811,2),(7,20201422,3),(8,20201688,4),(9,NULL,5);


DROP TABLE IF EXISTS `orders_detail`;


CREATE TABLE `orders_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`orderId` int(11) DEFAULT NULL,
`productId` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;


insert into `orders_detail`(`id`,`orderId`,`productId`) values (1,1,1),(2,1,2),(3,1,3),(4,2,3),(5,2,1),(6,3,2);


DROP TABLE IF EXISTS `product`;


CREATE TABLE `product` (
`pid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(25) DEFAULT NULL,
`price` double DEFAULT NULL,
PRIMARY KEY (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;


insert into `product`(`pid`,`name`,`price`) values (1,'Java教程',128),(2,'C語言教程',138),(3,'Python教程',132.35);

2. 建立持久化類

Order 類程式碼如下。

package net.biancheng.po;


import java.util.List;


public class Order {
private int oid;
private int ordernum;
private List<Product> products;


/*省略setter和getter方法*/


@Override
public String toString() {
return "Order [id=" + oid + ", ordernum=" + ordernum + ", products=" + products + "]";
}


}

Product 類方法如下。

package net.biancheng.po;


import java.util.List;


public class Product {
private int pid;
private String name;
private Double price;


// 多對多中的一個一對多
private List<Order> orders;


/*省略setter和getter方法*/


@Override
public String toString() {
return "Product [id=" + pid + ", name=" + name + ", price=" + price + "]";
}
}

3. 建立介面和對映檔案

OrderMapper 介面程式碼如下。

package net.biancheng.mapper;


import java.util.List;


import net.biancheng.po.Order;


public interface OrderMapper {
public List<Order> selectAllOrdersAndProducts();
}

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="net.biancheng.mapper.OrderMapper">


<resultMap type="net.biancheng.po.Order" id="orderMap">
<id property="oid" column="oid" />
<result property="ordernum" column="ordernum" />


<collection property="products"
ofType="net.biancheng.po.Product">
<id property="pid" column="pid" />
<result property="name" column="name" />
<result property="price" column="price" />
</collection>
</resultMap>


<select id="selectAllOrdersAndProducts" parameterType="Integer"
resultMap="orderMap">
SELECT o.oid,o.`ordernum`,p.`pid`,p.`name`,p.`price` FROM
`order` o
INNER JOIN orders_detail od ON o.oid=od.`orderId`
INNER JOIN
product p
ON p.pid = od.`productId`
</select>


</mapper>

4. 建立測試類

測試類程式碼如下。

package net.biancheng.test;


import java.io.IOException;
import java.io.InputStream;
import java.util.List;


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 net.biancheng.mapper.OrderMapper;
import net.biancheng.po.Order;


public class Test {
public static void main(String[] args) throws IOException {
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
SqlSession ss = ssf.openSession();


List<Order> orderList = ss.getMapper(OrderMapper.class).selectAllOrdersAndProducts();
for (Order or : orderList) {
System.out.println(or);
}
}
}

執行結果如下。

DEBUG [main] - ==>  Preparing: SELECT o.oid,o.`ordernum`,p.`pid`,p.`name`,p.`price` FROM `order` o INNER JOIN orders_detail od ON o.oid=od.`orderId` INNER JOIN product p ON p.pid = od.`productId`
DEBUG [main] - ==> Parameters:
DEBUG [main] - <==      Total: 6
Order [id=1, ordernum=20200107, products=[Product [id=1, name=Java教程, price=128.0], Product [id=2, name=C語言教程, price=138.0], Product [id=3, name=Python教程, price=132.35]]]
Order [id=2, ordernum=20200806, products=[Product [id=3, name=Python教程, price=132.35], Product [id=1, name=Java教程, price=128.0]]]
Order [id=3, ordernum=20206702, products=[Product [id=2, name=C語言教程, price=138.0]]]