在实际开发中,会存在很多表。比如一个电商项目可能有:分类表、产品表、顾客表、订单表等。这些表之间是存在关系的。

表与表之间的三种关系


判断技巧 例子
一对多 分别从两个角度思考问题:比如班级对学生。
从班级的角度看问题:一个班级可以对应很多学生。
从学生角度看问题:一个学生只能对应一个班级。
班级对学生、部门对员工、用户对订单、人对银行卡、客户和订单、分类和商品
多对多 学生与课程、用户与角色
一对一 人对身份证

一对多

建表原则

先分清楚一方和多方,根据上面表格的判断技巧来判断,这样很容易搞清楚。在多方的表中添加一个字段,作为该表的外键,指向一方的主键。
image.png
例如一个人可以有很多银行卡,一个银行卡只能对应一个人。在从表(多方)里面新建一个外键指向主表(一方)的主键。这里从表是bank_card 、主表是person。bank_card里面的person_id做为外键指向person表的主键。

SQL语句

查询所有人对应的银行卡信息

一个人可以拥有多个银行卡,查询的是人,从person表出发(所谓从哪里出发指的是FROM 后先跟什么表)

  1. SELECT
  2. person.* ,
  3. bank_card.id AS bank_id,bank_card.`no`,bank_card.amount
  4. FROM person LEFT JOIN bank_card ON person.id = bank_card.fn_person_id

本节末尾有其对应的JavaBean及SQL样例数据。

MyBatis对应的mapper

  1. <select id="getPersonBankCard" resultMap="bankCards">
  2. SELECT
  3. person.* ,
  4. bank_card.id AS bank_id,bank_card.`no`,bank_card.amount
  5. FROM person LEFT JOIN bank_card ON person.id = bank_card.fn_person_id
  6. </select>
  7. <resultMap id="bankCards" type="com.lff.beans.Person">
  8. <id property="id" column="id" />
  9. <result property="name" column="name" />
  10. <result property="age" column="age" />
  11. <collection property="bankCards" ofType="com.lff.beans.BankCard">
  12. <id property="id" column="bank_id" />
  13. <result property="no" column="no" />
  14. <result property="amount" column="amount" />
  15. </collection>
  16. </resultMap>

外界使用

  1. try(SqlSession session = MyBatisUtils.openSession()){
  2. List<Person> personList = session.selectList("person.getPersonBankCard");
  3. System.out.println(personList);
  4. }

查询每张银行卡把关联的人也查出来

从bank_card银行卡出发,根据条件关联其对应的人

  1. SELECT
  2. bank_card.*,
  3. person.*
  4. FROM bank_card LEFT JOIN person ON person.id = bank_card.fn_person_id

多对多

如果是多对多,通常会创建一个中间表,把表的关系拆成两个一对多。在中间表至少包含两个字段,作为该表的外键指向一方表的主键。中间表不仅能有效的节省存储空间也能更容易的维护表与表之间的关系。
例子:人与角色之间的关系,一个人可以有很多个角色。一个角色可以有很多个人。
image.png

中间表至少包含两个字段:person_id外键、role_id外键。这两个外键作为联合主键使用。
如上表,person表里面的Jack既有作为丈夫的角色也有作为厨师的角色

SQL语句

查询每个人都对应哪些角色

从person表出发,关联中间表后,再查询角色表

  1. SELECT
  2. person.*,
  3. role.`name` AS role_name,role.duty
  4. FROM person LEFT JOIN person_role ON person.id = person_role.person_id
  5. LEFT JOIN role ON role.id = person_role.role_id

MyBatis对应的mapper

  1. <select id="getPersonRoles" resultMap="roles">
  2. SELECT
  3. person.*,
  4. role.`name` AS role_name,role.duty
  5. FROM person LEFT JOIN person_role ON person.id = person_role.person_id
  6. LEFT JOIN role ON role.id = person_role.role_id
  7. </select>
  8. <resultMap id="roles" type="com.lff.beans.Person">
  9. <id property="id" column="id" />
  10. <result property="name" column="name" />
  11. <result property="age" column="age" />
  12. <collection property="roles" ofType="com.lff.beans.Role">
  13. <result property="name" column="role_name" />
  14. <result property="duty" column="duty" />
  15. </collection>
  16. </resultMap>

外界使用

  1. try(SqlSession session = MyBatisUtils.openSession()){
  2. List<Person> personList = session.selectList("person.getPersonRoles");
  3. System.out.println(personList);
  4. }

查询每个角色都有什么人

SQL语句,从role角色表出发,先关联中间表,关联后再查询person表

  1. SELECT
  2. role.id AS role_id ,role.`name` AS role_name ,role.duty,
  3. person.id AS person_id, person.`name` AS person_name,person.age
  4. FROM role LEFT JOIN person_role ON role.id = person_role.role_id
  5. LEFT JOIN person ON person.id = person_role.person_id

一对一

建表原则:

  • 可以都放在一张表中
  • 也可以在任意一方添加一个外键指向另一方的主键。从表的唯一外键和主表的主键,形成主外键关系, 外键唯一用UNIQUE修饰

示例:人和人的身份证
image.png
id_card有一个外键引用person表的id。
每一个人都有一个唯一的身份证号

SQL查询语句

查询所有的人以及对应的身份证

从person表出发,根据条件查询其对应的身份证

  1. SELECT person.* , id_card.`no`,id_card.address,id_card.person_id FROM person JOIN id_card ON person.id = id_card.person_id

MyBatis对应的mapper

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="person">
  6. <select id="personList" resultMap="personMap">
  7. SELECT person.* , id_card.`no`,id_card.address,id_card.person_id FROM person JOIN id_card ON person.id = id_card.person_id
  8. </select>
  9. <resultMap id="personMap" type="com.lff.beans.Person">
  10. <id property="id" column="id" />
  11. <result property="name" column="name" />
  12. <result property="age" column="age" />
  13. <association property="idCard" javaType="com.lff.beans.IdCard">
  14. <id property="id" column="id" />
  15. <result property="no" column="no" />
  16. <result property="address" column="address" />
  17. </association>
  18. </resultMap>
  19. </mapper>

外界使用

  1. try(SqlSession session = MyBatisUtils.openSession()){
  2. List<Person> personList = session.selectList("person.personList");
  3. }

查询所有的身份证以及对应的人

从id_card表出发,根据条件查询出对应的人。

  1. SELECT id_card.* ,person.`name`,person.age FROM id_card JOIN person ON id_card.person_id = person.id

MyBatis对应的mapper

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="idCard">
  6. <select id="idCardList" resultMap="idCardMap">
  7. SELECT id_card.* ,person.`name`,person.age FROM id_card JOIN person ON id_card.person_id = person.id
  8. </select>
  9. <resultMap id="idCardMap" type="com.lff.beans.IdCard">
  10. <id property="id" column="id" />
  11. <result property="no" column="no" />
  12. <result property="address" column="address" />
  13. <association property="person" javaType="com.lff.beans.Person">
  14. <id property="id" column="id" />
  15. <result property="name" column="name" />
  16. <result property="age" column="age" />
  17. </association>
  18. </resultMap>
  19. </mapper>

外界使用

  1. try(SqlSession session = MyBatisUtils.openSession()){
  2. List<IdCard> idCardList = session.selectList("idCard.idCardList");
  3. }


综合案例

查询出人对应的信息,包括姓名、年龄、身份证信息、银行卡信息、角色信息。

SQL语句

  1. SELECT
  2. person.* ,
  3. id_card.`no` AS id_no,id_card.address,
  4. bank_card.id AS bank_card_id,bank_card.`no` AS bank_card_no,bank_card.amount ,
  5. role.`name` AS role_name,role.duty
  6. FROM person JOIN id_card ON person.id = id_card.person_id
  7. LEFT JOIN bank_card ON person.id = bank_card.fn_person_id
  8. LEFT JOIN person_role ON person.id = person_role.person_id
  9. LEFT JOIN role ON role.id = person_role.role_id
  • 因为要查询出的是人,所以FROM后应先跟person表
  • 使用join关联出身份证信息
  • 使用LEFT JOIN查询出银行卡信息
  • LEFT JOIN person_role ON person.id = person_role.person_id

多对多的情况先关联中间表,先有中间表后,后面才能使用中间表里面的信息
当有多个表的字段相同时,要起一个别名,否则查询出来的字段会覆盖前面的。

MyBatis对应的mapper

  1. <select id="getPersonAllInfo" resultMap="allInfo">
  2. SELECT
  3. person.* ,
  4. id_card.`no` AS id_no,id_card.address,
  5. bank_card.id AS bank_card_id,bank_card.`no` AS bank_card_no,bank_card.amount ,
  6. role.`name` AS role_name,role.duty
  7. FROM person JOIN id_card ON person.id = id_card.person_id
  8. LEFT JOIN bank_card ON person.id = bank_card.fn_person_id
  9. LEFT JOIN person_role ON person.id = person_role.person_id
  10. LEFT JOIN role ON role.id = person_role.role_id
  11. </select>
  12. <resultMap id="allInfo" type="com.lff.beans.Person">
  13. <id property="id" column="id" />
  14. <result property="name" column="name" />
  15. <result property="age" column="age" />
  16. <!-- 关联的身份证信息:idCard为Person类的属性名-->
  17. <association property="idCard" javaType="com.lff.beans.IdCard">
  18. <!-- 这里的属性property都是类IdCard的属性名,column是数据库查询出来的字段-->
  19. <result property="no" column="id_no" />
  20. <result property="address" column="address" />
  21. </association>
  22. <!-- 当属性值是一个列表时如Person类的 List<BankCard> bankCards,使用collection标签,ofType对应列表里面每一个对象对应的类-->
  23. <collection property="bankCards" ofType="com.lff.beans.BankCard">
  24. <!-- 这里的属性property都是类BankCard的属性名,column是数据库查询出来的字段-->
  25. <result property="no" column="bank_card_no" />
  26. <result property="amount" column="amount" />
  27. </collection>
  28. <collection property="roles" ofType="com.lff.beans.Role">
  29. <result property="name" column="role_name" />
  30. <result property="duty" column="duty" />
  31. </collection>
  32. </resultMap>

外界使用

  1. try(SqlSession session = MyBatisUtils.openSession()){
  2. List<Person> personList = session.selectList("person.getPersonAllInfo");
  3. System.out.println(personList);
  4. }

本节使用的SQL样例

  1. SET NAMES utf8mb4;
  2. SET FOREIGN_KEY_CHECKS = 0;
  3. -- ----------------------------
  4. -- Table structure for bank_card
  5. -- ----------------------------
  6. DROP TABLE IF EXISTS `bank_card`;
  7. CREATE TABLE `bank_card` (
  8. `id` int(11) NOT NULL AUTO_INCREMENT,
  9. `no` int(11) NOT NULL,
  10. `amount` decimal(18,2) DEFAULT NULL,
  11. `fn_person_id` int(11) DEFAULT NULL,
  12. PRIMARY KEY (`id`),
  13. KEY `fn_person_id` (`fn_person_id`),
  14. CONSTRAINT `fn_person_id` FOREIGN KEY (`fn_person_id`) REFERENCES `person` (`id`)
  15. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
  16. -- ----------------------------
  17. -- Records of bank_card
  18. -- ----------------------------
  19. BEGIN;
  20. INSERT INTO `bank_card` VALUES (1, 123456, 1000.00, 1);
  21. INSERT INTO `bank_card` VALUES (2, 234567, 300.00, 1);
  22. INSERT INTO `bank_card` VALUES (3, 345678, 200.00, 3);
  23. INSERT INTO `bank_card` VALUES (4, 456789, 500.00, 4);
  24. COMMIT;
  25. -- ----------------------------
  26. -- Table structure for id_card
  27. -- ----------------------------
  28. DROP TABLE IF EXISTS `id_card`;
  29. CREATE TABLE `id_card` (
  30. `id` int(11) NOT NULL AUTO_INCREMENT,
  31. `no` int(30) DEFAULT NULL,
  32. `address` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
  33. `person_id` int(11) NOT NULL,
  34. PRIMARY KEY (`id`),
  35. KEY `fk_person_id` (`person_id`),
  36. CONSTRAINT `fk_person_id` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
  37. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
  38. -- ----------------------------
  39. -- Records of id_card
  40. -- ----------------------------
  41. BEGIN;
  42. INSERT INTO `id_card` VALUES (1, 123999, '北京市朝阳区。。。', 1);
  43. INSERT INTO `id_card` VALUES (2, 123888, '北京市昌平区。。。', 2);
  44. INSERT INTO `id_card` VALUES (3, 123777, '北京市海淀区。。。', 3);
  45. INSERT INTO `id_card` VALUES (4, 123666, '北京市通州区。。。', 4);
  46. COMMIT;
  47. -- ----------------------------
  48. -- Table structure for person
  49. -- ----------------------------
  50. DROP TABLE IF EXISTS `person`;
  51. CREATE TABLE `person` (
  52. `id` int(11) NOT NULL AUTO_INCREMENT,
  53. `name` varchar(30) CHARACTER SET utf8mb4 DEFAULT NULL,
  54. `age` int(3) DEFAULT NULL,
  55. PRIMARY KEY (`id`),
  56. KEY `id` (`id`),
  57. KEY `age` (`age`)
  58. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
  59. -- ----------------------------
  60. -- Records of person
  61. -- ----------------------------
  62. BEGIN;
  63. INSERT INTO `person` VALUES (1, 'Jack', 18);
  64. INSERT INTO `person` VALUES (2, 'Mike', 22);
  65. INSERT INTO `person` VALUES (3, 'Jose', 28);
  66. INSERT INTO `person` VALUES (4, 'Cliff', 35);
  67. COMMIT;
  68. -- ----------------------------
  69. -- Table structure for person_role
  70. -- ----------------------------
  71. DROP TABLE IF EXISTS `person_role`;
  72. CREATE TABLE `person_role` (
  73. `person_id` int(11) NOT NULL,
  74. `role_id` int(11) NOT NULL,
  75. PRIMARY KEY (`person_id`,`role_id`),
  76. KEY `r_id` (`role_id`),
  77. CONSTRAINT `p_id` FOREIGN KEY (`person_id`) REFERENCES `person` (`id`),
  78. CONSTRAINT `r_id` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`)
  79. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
  80. -- ----------------------------
  81. -- Records of person_role
  82. -- ----------------------------
  83. BEGIN;
  84. INSERT INTO `person_role` VALUES (2, 1);
  85. INSERT INTO `person_role` VALUES (1, 2);
  86. INSERT INTO `person_role` VALUES (1, 3);
  87. COMMIT;
  88. -- ----------------------------
  89. -- Table structure for role
  90. -- ----------------------------
  91. DROP TABLE IF EXISTS `role`;
  92. CREATE TABLE `role` (
  93. `id` int(11) NOT NULL AUTO_INCREMENT,
  94. `name` varchar(50) COLLATE utf8mb4_bin NOT NULL,
  95. `duty` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
  96. PRIMARY KEY (`id`)
  97. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
  98. -- ----------------------------
  99. -- Records of role
  100. -- ----------------------------
  101. BEGIN;
  102. INSERT INTO `role` VALUES (1, '程序员', '编码大神');
  103. INSERT INTO `role` VALUES (2, '丈夫', '爱妻子');
  104. INSERT INTO `role` VALUES (3, '厨师', '能够做一手好菜');
  105. INSERT INTO `role` VALUES (4, '摄影爱好者', '拍照达人');
  106. COMMIT;
  107. SET FOREIGN_KEY_CHECKS = 1;

本节涉及的JavaBean

Person类

  1. package com.lff.beans;
  2. import java.util.List;
  3. public class Person {
  4. private Integer id;
  5. private String name;
  6. private Integer age;
  7. private IdCard idCard;
  8. private List<BankCard> bankCards;
  9. private List<Role> roles;
  10. public Integer getId() {
  11. return id;
  12. }
  13. public void setId(Integer id) {
  14. this.id = id;
  15. }
  16. public String getName() {
  17. return name;
  18. }
  19. public void setName(String name) {
  20. this.name = name;
  21. }
  22. public Integer getAge() {
  23. return age;
  24. }
  25. public void setAge(Integer age) {
  26. this.age = age;
  27. }
  28. public IdCard getIdCard() {
  29. return idCard;
  30. }
  31. public void setIdCard(IdCard idCard) {
  32. this.idCard = idCard;
  33. }
  34. public List<BankCard> getBankCards() {
  35. return bankCards;
  36. }
  37. public void setBankCards(List<BankCard> bankCards) {
  38. this.bankCards = bankCards;
  39. }
  40. public List<Role> getRoles() {
  41. return roles;
  42. }
  43. public void setRoles(List<Role> roles) {
  44. this.roles = roles;
  45. }
  46. }

银行卡类

  1. package com.lff.beans;
  2. import java.math.BigDecimal;
  3. public class BankCard {
  4. private Integer id;
  5. private String no;
  6. private BigDecimal amount;
  7. private Person person;
  8. public Integer getId() {
  9. return id;
  10. }
  11. public void setId(Integer id) {
  12. this.id = id;
  13. }
  14. public String getNo() {
  15. return no;
  16. }
  17. public void setNo(String no) {
  18. this.no = no;
  19. }
  20. public BigDecimal getAmount() {
  21. return amount;
  22. }
  23. public void setAmount(BigDecimal amount) {
  24. this.amount = amount;
  25. }
  26. public Person getPerson() {
  27. return person;
  28. }
  29. public void setPerson(Person person) {
  30. this.person = person;
  31. }
  32. }

身份证类

  1. package com.lff.beans;
  2. public class IdCard {
  3. private Integer id;
  4. private String no;
  5. private String address;
  6. private Person person;
  7. public Integer getId() {
  8. return id;
  9. }
  10. public void setId(Integer id) {
  11. this.id = id;
  12. }
  13. public String getNo() {
  14. return no;
  15. }
  16. public void setNo(String no) {
  17. this.no = no;
  18. }
  19. public String getAddress() {
  20. return address;
  21. }
  22. public void setAddress(String address) {
  23. this.address = address;
  24. }
  25. public Person getPerson() {
  26. return person;
  27. }
  28. public void setPerson(Person person) {
  29. this.person = person;
  30. }
  31. }

角色类

  1. package com.lff.beans;
  2. import java.util.List;
  3. public class Role {
  4. private Integer id;
  5. private String name;
  6. private String duty;
  7. private List<Person> persons;
  8. public Integer getId() {
  9. return id;
  10. }
  11. public void setId(Integer id) {
  12. this.id = id;
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public String getDuty() {
  21. return duty;
  22. }
  23. public void setDuty(String duty) {
  24. this.duty = duty;
  25. }
  26. public List<Person> getPersons() {
  27. return persons;
  28. }
  29. public void setPersons(List<Person> persons) {
  30. this.persons = persons;
  31. }
  32. }