SpringDataJPA(三):多表操作,复杂查询

一、Specifications动态查询

有时我们在查询某个实体的时候,给定的条件是不固定的,这时就需要动态构建相应的查询语句,在Spring Data JPA中可以通过JpaSpecificationExecutor接口查询。相比JPQL,其优势是类型安全,更加的面向对象。

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;

/**
 *	JpaSpecificationExecutor中定义的方法列表
 **/
 public interface JpaSpecificationExecutor<T> {
    
    
   	// 根据条件查询一个对象
 	T findOne(Specification<T> spec);
   	// 根据条件查询集合
 	List<T> findAll(Specification<T> spec);
   	// 根据条件分页查询
 	Page<T> findAll(Specification<T> spec, Pageable pageable);
   	// 排序查询
 	List<T> findAll(Specification<T> spec, Sort sort);
   	// 统计查询
 	long count(Specification<T> spec);
}

对于JpaSpecificationExecutor,这个接口基本是围绕着Specification接口来定义的。我们可以简单的理解为,Specification构造的就是查询条件。

Specification接口中只定义了如下一个方法:

 	//构造查询条件
    /**
    *	root	:Root接口,代表查询的根对象,可以通过root获取实体中的属性
    *	query	:代表一个顶层查询对象,用来自定义查询方式(一般不用)
    *	cb		:用来构建查询,此对象里封装有很多查询条件方法
    **/
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb);

栗子

src\main\java\top\onefine\dao\CustomerDao.java:

package top.onefine.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import top.onefine.domain.Customer;

public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
    
    
}

src\test\java\top\onefine\dao\CustomerDaoTest.java:

package top.onefine.dao;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import top.onefine.domain.Customer;

import javax.persistence.criteria.*;

import java.util.List;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class CustomerDaoTest {
    
    

    @SuppressWarnings("All")
    @Autowired
    private CustomerDao customerDao;

    /**
     * 单条件精确查询demo——自定义查询条件
     *      1. 实现Specification接口,需要提供的泛型是查询的对象类型
     *      2. 实现接口中的toPredicate方法,用于构造查询条件
     *      3. 需要借助方法参数中的两个参数
     *          - Root: 获取需要查询的对象属性
     *          - CriteriaBuilder:用于构造查询条件,内部封装了很多的查询条件(模糊匹配,精准匹配)
     */
    @Test
    public void testFindOne() {
    
    
        // 匿名内部类
//        Specification<Customer> specification = new Specification<Customer>() {
    
    
//            @Override
//            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
    
    
//                // 根据客户名称查询
//                // 1. 获取比较的属性
//                Path<Object> custName = root.get("custName");  // Root对象中获取用于比较的属性名称
//                // 2. 构造查询条件    select * from cst_customer where cust_name = "one fine"
//                //      equal表示进行精准匹配,第一个参数表示需要比较的属性(Path对象),第二个参数表示比较属性的取值
//                @SuppressWarnings("")
//                Predicate predicate = criteriaBuilder.equal(custName, "one fine");// CriteriaBuilder对象中构造查询方式
//                return predicate;
//            }
//        };
//        Customer customer = customerDao.findOne(specification);

        // Lambda简化
        Customer customer = customerDao.findOne((root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(root.get("custName"), "one fine"));
        System.out.println(customer);
    }

    /** 多条件精确查询demo——根据客户名和客户所属行业查询
     */
    @Test
    public void testFindOne_() {
    
    
        Customer customer = customerDao.findOne((root, criteriaQuery, criteriaBuilder) -> {
    
    
            // 1. 构造客户名的精准匹配查询
            Predicate predicate1 = criteriaBuilder.equal(root.get("custName"), "one fine");
            // 2. 构造所属行业的精准匹配查询
            Predicate predicate2 = criteriaBuilder.equal(root.get("custIndustry"), "软件");
            // 3. 将以上两个查询联系起来:组合
            //  - 与关系:and   交集
            //  - 或关系:or    并集
            return criteriaBuilder.and(predicate1, predicate2);
        });
        System.out.println(customer);
    }

    /**
     * 模糊匹配,根据客户名称模糊匹配,返回客户列表
     *  - equal:直接得到Path对象(属性),然后进行比较即可
     *  - gt, lt, ge, le, like...:得到Path对象,根据Path指定需要比较的参数类型,再去进行比较
     *      指定参数类型: path.as(类型的字节码对象)
     */
    @Test
    public void testFindAll() {
    
    
//        Specification<Customer> specification = new Specification<Customer>() {
    
    
//            @Override
//            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
    
    
//                Path<Object> custName = root.get("custName");
//                Expression<String> custNameExpression = custName.as(String.class);
//                @SuppressWarnings("")
//                Predicate predicate = criteriaBuilder.like(custNameExpression, "one fine");  // 查询方式:模糊匹配
//                return predicate;
//            }
//        };
//        List<Customer> customers = customerDao.findAll(specification);

//        List<Customer> customers = customerDao.findAll((Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) ->
//            criteriaBuilder.like(root.get("custName").as(String.class), "one fine"));
        List<Customer> customers = customerDao.findAll((root, criteriaQuery, criteriaBuilder) ->
                criteriaBuilder.like(root.get("custName").as(String.class), "%fine%"));  // 包含"fine"的
        for (Customer customer : customers)
            System.out.println(customer);
    }

    /**
     * 排序
     */
    @Test
    public void testFindAll_desc() {
    
    

        // 创建排序对象
        // 第一个参数:排序的顺序
        // - Sort.Direction.DESC 倒序
        // - Sort.Direction.ASC 升序
        // 第二个参数:排序的属性名称
        Sort sort = new Sort(Sort.Direction.DESC, "custId");  // 查询结果按照id倒序
        // 添加排序
        List<Customer> customers = customerDao.findAll((root, criteriaQuery, criteriaBuilder) ->
                criteriaBuilder.like(root.get("custName").as(String.class), "one fine"), sort);
        for (Customer customer : customers)
            System.out.println(customer);
    }

    /**
     * 分页查询
     *  - findAll(Specification, Pageable)  带条件的分页
     *  - findAll(Pageable) 不带条件的分页
     * 返回Page对象,是SpringDataJPA封装好的pageBean对象,可以从中获取到数据列表和总条数等
     */
    @Test
    public void testFindAll_page() {
    
    
        Specification<Customer> specification = null;  // 无查询条件
        // Pageable:分页参数
        // PageRequest对象是Pageable接口的实现类
        //  - 第一个参数:查询的页码(从0开始)
        //  - 第二个参数:每页查询的记录条数

        Pageable pageable = new PageRequest(1, 2);  // 第2页(0开始编号),每页显示2个数据

        Page<Customer> customerPage = customerDao.findAll(specification, pageable);  // 无查询条件
        System.out.println("" + customerPage.getTotalElements() + "\n" +  // 记录总数
                            "" + customerPage.getTotalPages() + "\n" +  // 总页数
                            "" + customerPage.getSize() + "\n" +  // 分页大小
                            "" + customerPage.getContent());  // 结果列表

    }

    /**
     * 统计查询
     */
    @Test
    public void testCount() {
    
    

        long count = customerDao.count((root, criteriaQuery, criteriaBuilder) ->
                criteriaBuilder.like(root.get("custName").as(String.class), "%fine"));  // 以"fine"结束的
        System.out.println(count);
    }
}

方法对应关系

方法名称 Sql对应关系
equle filed = value
gt(greaterThan ) filed > value
lt(lessThan ) filed < value
ge(greaterThanOrEqualTo ) filed >= value
le( lessThanOrEqualTo) filed <= value
notEqule filed != value
like filed like value
notLike filed not like value

二、多表设计

2.1 表之间关系的划分

数据库中多表之间存在着三种关系,如图所示。

在这里插入图片描述

从图可以看出,系统设计的三种实体关系分别为:多对多、一对多和一对一(一般不使用)关系。注意:一对多关系可以看为两种: 即一对多,多对一;所以说四种更精确。

一对多关系中:习惯将一的一方称作主表,将多的一方称之为从表。用外键描述这种关系,需要在从表中新建一个属性作为外键,其取值来源于主表的主键。

多对多关系中:用中间表(第三章表)来描述这种关系,中间表中至少应该由两个字段组成,这两个字段作为外键指向两张表的主键,且这两个字段又组成了联合主键。

明确:
这里只涉及实际开发中常用的关联关系,一对多和多对多。而一对一的情况,在实际开发中几乎不用。

实体类中的关系:

  • 包含关系:可以通过实体类中的包含关系描述表关系(一对一、一对多、多对一、多对多)
  • 继承关系

2.2 在JPA框架中表关系的分析步骤

在实际开发中,我们数据库的表难免会有相互的关联关系,在操作表的时候就有可能会涉及到多张表的操作。而在这种实现了ORM思想的框架中(如JPA),可以让我们通过操作实体类就实现对数据库表的操作。所以今天我们的学习重点是:掌握配置实体之间的关联关系。

第一步:首先确定两张表之间的关系。

  • 如果关系确定错了,后面做的所有操作就都不可能正确。

第二步:在数据库中实现两张表的关系(用外键或中间表描述)

第三步:在实体类中描述出两个实体的关系(实体类的包含关系)

第四步:配置出实体类和数据库表的关系映射(重点)

三、JPA中的一对多

3.1 示例分析

我们采用的示例为客户和联系人。

客户:指的是一家公司,我们记为A。

联系人:指的是A公司中的员工。

在不考虑兼职的情况下,公司和员工的关系即为一对多。即一个客户具有多个联系人,一个联系人从属于一家公司。

3.2 表关系建立

在一对多关系中,我们习惯把一的一方称之为主表,把多的一方称之为从表。在数据库中建立一对多的关系,需要使用数据库的外键约束。

什么是外键?
指的是从表中有一列,取值参照主表的主键,这一列就是外键。

一对多数据库关系的建立,如下图所示:
在这里插入图片描述

这里一对多的栗子中,主表是客户表,从表是联系人表(需要添加外键)。

/*创建客户表*/
CREATE TABLE cst_customer (
  cust_id bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  cust_name varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
  cust_source varchar(32) DEFAULT NULL COMMENT '客户信息来源',
  cust_industry varchar(32) DEFAULT NULL COMMENT '客户所属行业',
  cust_level varchar(32) DEFAULT NULL COMMENT '客户级别',
  cust_address varchar(128) DEFAULT NULL COMMENT '客户联系地址',
  cust_phone varchar(64) DEFAULT NULL COMMENT '客户联系电话',
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=94 DEFAULT CHARSET=utf8;

/*创建联系人表*/
CREATE TABLE cst_linkman (
  lkm_id bigint(32) NOT NULL AUTO_INCREMENT COMMENT '联系人编号(主键)',
  lkm_name varchar(16) DEFAULT NULL COMMENT '联系人姓名',
  lkm_gender char(1) DEFAULT NULL COMMENT '联系人性别',
  lkm_phone varchar(16) DEFAULT NULL COMMENT '联系人办公电话',
  lkm_mobile varchar(16) DEFAULT NULL COMMENT '联系人手机',
  lkm_email varchar(64) DEFAULT NULL COMMENT '联系人邮箱',
  lkm_position varchar(16) DEFAULT NULL COMMENT '联系人职位',
  lkm_memo varchar(512) DEFAULT NULL COMMENT '联系人备注',
  lkm_cust_id bigint(32) NOT NULL COMMENT '客户id(外键)',
  PRIMARY KEY (`lkm_id`),
  KEY `FK_cst_linkman_lkm_cust_id` (`lkm_cust_id`),
  CONSTRAINT `FK_cst_linkman_lkm_cust_id` FOREIGN KEY (`lkm_cust_id`) REFERENCES `cst_customer` (`cust_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

3.3 实体类关系建立以及映射配置

要点:

客户:在客户的实体类中包含一个联系人的集合
联系人:在联系人的实体类中包含有一个客户的对象

在实体类中,由于客户是少的一方,它应该包含多个联系人,所以实体类要体现出客户中有多个联系人的信息,代码如下:

package top.onefine.domain;

import lombok.*;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * 1. 实体类和表的映射关系
 *      -@Eitity
 *      -@Table
 * 2. 类中属性和数据库表中字段的映射关系
 *      -@Id 主键
 *      -@GeneratedValue 主键生成策略
 *      -@Column
 */
@Entity
@Table(name = "cst_customer")
@Data  // 使用@Getter和@Setter,但是要自己生成toString方法
//@Getter
//@Setter
@NoArgsConstructor
public class Customer {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;
    @Column(name = "cust_address")
    private String custAddress;
    @Column(name = "cust_industry")
    private String custIndustry;
    @Column(name = "cust_level")
    private String custLevel;
    @Column(name = "cust_name")
    private String custName;
    @Column(name = "cust_phone")
    private String custPhone;
    @Column(name = "cust_source")
    private String custSource;

    // 配置客户和联系人之间的关系(一对多关系)
    /*
        使用注解的形式配置多表关系:
            1. 声明关系
                - @OneToMany:配置一对多关系
                    targetEntity:对方对象的字节码对象
            2. 配置外键(或中间表)
                - @JoinColumn:配置外键
                    name:从表 外键字段名称
                    referencedColumnName:参照的 主表 的主键字段名称

        注:在客户实体类上(一的一方)添加了外键的配置,所以对于客户而言,也具备了维护外键的作用

     */
    @OneToMany(targetEntity = LinkMan.class)
    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    /*
        放弃外键维护权
            mappedBy: 对方配置关系的属性名称
                表示参照对方的属性来做
     */
//    @OneToMany(mappedBy = "customer")
    private Set<LinkMan> linkMans = new HashSet<>();

    // 一定要自己写,不要使用lombok提供的
//    @Override
//    public String toString() {
    
    
//        return "Customer{" +
//                "custId=" + custId +
//                ", custAddress='" + custAddress + '\'' +
//                ", custIndustry='" + custIndustry + '\'' +
//                ", custLevel='" + custLevel + '\'' +
//                ", custName='" + custName + '\'' +
//                ", custPhone='" + custPhone + '\'' +
//                ", custSource='" + custSource + '\'' +
//                ", linkMans=" + linkMans +
//                '}';
//    }
}

由于联系人是多的一方,在实体类中要体现出,每个联系人只能对应一个客户,代码如下:

package top.onefine.domain;

import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Entity
@Table(name = "cst_linkman")
@Data
@NoArgsConstructor
public class LinkMan {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "lkm_id")
    private Long lkmId;  // 联系人编号
    @Column(name = "lkm_name")
    private String lkmName;  // 联系人姓名
    @Column(name = "lkm_gender")
    private String lkmGender;  // 联系人性别  // 对应数据库表中字段char(1)
    @Column(name = "lkm_phone")
    private String lkmPhone;  // 联系人办公电话
    @Column(name = "lkm_mobile")
    private String lkmMobile;  // 联系人手机
    @Column(name = "lkm_email")
    private String lkmEmail;  // 联系人邮箱
    @Column(name = "lkm_position")
    private String lkmPosition;  // 联系人职位
    @Column(name = "lkm_memo")
    private String lkmMemo;  // 联系人备注

    // 配置联系人到客户的多对一关系
    /*
        使用注解的形式配置多对一关系
            1. 配置表关系
                - @ManyToOne:配置多对一关系
                    targetEntity:对方对象的字节码对象
            2. 配置外键(或中间表)

        注:配置外键的过程,配置到了多的一方,就会在多的一方维护外键
     */
    @ManyToOne(targetEntity = Customer.class)
    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    private Customer customer;
}
其他配置

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>top.onefine</groupId>
    <artifactId>jpa_day3_one2mant</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--        <project.hibernate.version>5.4.14.Final</project.hibernate.version>-->
<!--        <project.hibernate.version>5.0.7.Final</project.hibernate.version>-->
        <project.hibernate.version>5.1.17.Final</project.hibernate.version>
        <project.spring.version>5.2.5.RELEASE</project.spring.version>
        <project.slf4j.version>1.7.30</project.slf4j.version>
        <project.log4j.version>1.2.17</project.log4j.version>
        <project.c3p0.version>0.9.5.5</project.c3p0.version>
        <project.mysql.version>8.0.19</project.mysql.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <!-- 以下两个是spring aop相关的坐标 -->
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
<!--            <version>1.9.5</version>-->
            <version>1.6.8</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${project.spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${project.spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${project.spring.version}</version>
        </dependency>

        <!-- spring对orm框架的支持包 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${project.spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${project.spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${project.spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${project.hibernate.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${project.hibernate.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <!--            <version>6.1.4.Final</version>-->
            <version>5.4.3.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${project.log4j.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${project.slf4j.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${project.slf4j.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>${project.c3p0.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <!-- Mysql and MariaDB -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${project.mysql.version}</version>
        </dependency>

        <!-- spring data jpa 的坐标 -->
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <!--            <version>2.2.6.RELEASE</version>-->
            <!--            <version>1.9.0.RELEASE</version>-->
            <version>1.11.23.RELEASE</version>
        </dependency>

        <!-- spring 提供的单元测试的坐标 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${project.spring.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- 以下两个 spring data jpa必须导入的坐标 -->
        <!-- https://mvnrepository.com/artifact/javax.el/javax.el-api -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.glassfish.web/javax.el -->
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

</project>

src\main\resources\applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/data/jpa
		http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!-- spring 和 spring data jpa 的配置 -->
    <!-- 1. 创建entityManagerFactory对象交给spring容器管理 -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"/>

        <!-- 配置扫描的包——实体类所在的包 -->
        <property name="packagesToScan" value="top.onefine.domain"/>

        <!-- 配置jpa的实现厂家 -->
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
        </property>

        <!-- JPA的供应商适配器 -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!-- 配置是否自动创建数据库表,这里false -->
                <property name="generateDdl" value="false"/>
                <!-- 指定数据库类型 -->
                <property name="database" value="MYSQL"/>
                <!-- 配置数据库方言,即数据库支持的特有语法 -->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
                <!-- 配置是否显示sql语句,默认在控制台 -->
                <property name="showSql" value="true"/>
            </bean>
        </property>

        <!-- 配置jpa的方言,高级特性 -->
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
        </property>

        <!-- 注入jpa的配置信息
            加载jpa的基本配置信息和jpa实现方式(如hibernate)的配置信息
            hibernate.hbm2ddl.auto: 自动创建数据库表
                create: 每次都从新创建数据库表
                update: 有表不会重新创建,没有表会重新创建表
        -->
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create</prop><!-- 暂时 -->
            </props>
        </property>
    </bean>

    <!-- 2. 创建数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--  连接参数 -->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/study_eesy?serverTimezone=UTC" />
        <property name="user" value="root" />
        <property name="password" value="963123" />

        <!-- 连接池参数 -->
        <property name="initialPoolSize" value="5" />
        <property name="maxPoolSize" value="8" />
        <property name="checkoutTimeout" value="3000" />
    </bean>

    <!-- 3. 整合spring dataJpa
            dao接口所在包
    -->
    <jpa:repositories base-package="top.onefine.dao"
                      transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory" />

    <!-- 4. 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!-- 4.txAdvice-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 5.aop-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* top.onefine.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>

    <!-- 5. 配置声明式事务 -->

    <!-- 6. 配置包扫描 -->
    <context:component-scan base-package="top.onefine" />
</beans>

src\main\java\top\onefine\dao\CustomerDao.java:

package top.onefine.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import top.onefine.domain.Customer;

public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
    
    
}

src\main\java\top\onefine\dao\LinkManDao.java:

package top.onefine.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import top.onefine.domain.LinkMan;

/**
 * 联系人dao接口
 */
public interface LinkManDao extends JpaRepository<LinkMan, Long>, JpaSpecificationExecutor<LinkMan> {
    
    
}

3.4 映射的注解说明

	@OneToMany:
   	作用:建立一对多的关系映射
    属性:
    	targetEntityClass:指定多的多方的类的字节码
    	mappedBy:指定从表实体类中引用主表对象的名称。
    	cascade:指定要使用的级联操作
    	fetch:指定是否采用延迟加载
    	orphanRemoval:是否使用孤儿删除

	@ManyToOne
    作用:建立多对一的关系
    属性:
    	targetEntityClass:指定一的一方实体类字节码
    	cascade:指定要使用的级联操作
    	fetch:指定是否采用延迟加载
    	optional:关联是否可选。如果设置为false,则必须始终存在非空关系。

	@JoinColumn
	作用:用于定义主键字段和外键字段的对应关系。
	属性:
		name:指定外键字段的名称
		referencedColumnName:指定引用主表的主键字段名称
		unique:是否唯一。默认值不唯一
		nullable:是否允许为空。默认值允许。
		insertable:是否允许插入。默认值允许。
		updatable:是否允许更新。默认值允许。
		columnDefinition:列的定义信息。

3.5 一对多的操作

3.5.1 添加

1 客户和联系人作为独立的数据保存到数据库中:
package top.onefine.dao;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import top.onefine.domain.Customer;
import top.onefine.domain.LinkMan;



@SuppressWarnings("All")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class One2ManyTest {
    
    

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private LinkManDao linkManDao;

    /**
     * 保存一个客户,保存一个联系人
     */
    @Test
    @Transactional  // 配置事务
    @Rollback(value = false)  // 设置不自动回滚
    public void testAdd() {
    
    
        Customer customer = new Customer();
        customer.setCustName("测试");
        customer.setCustLevel("重要");
        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("one fine");
       
        customerDao.save(customer);
        linkManDao.save(linkMan);
    }
}

效果:

Hibernate: alter table cst_linkman drop foreign key FKh9yp1nql5227xxcopuxqx2e7q
Hibernate: drop table if exists cst_customer
Hibernate: drop table if exists cst_linkman
Hibernate: create table cst_customer (cust_id bigint not null auto_increment, cust_address varchar(255), cust_industry varchar(255), cust_level varchar(255), cust_name varchar(255), cust_phone varchar(255), cust_source varchar(255), primary key (cust_id))
Hibernate: create table cst_linkman (lkm_id bigint not null auto_increment, lkm_email varchar(255), lkm_gender varchar(255), lkm_memo varchar(255), lkm_mobile varchar(255), lkm_name varchar(255), lkm_phone varchar(255), lkm_position varchar(255), lkm_cust_id bigint, primary key (lkm_id))
Hibernate: alter table cst_linkman add constraint FKh9yp1nql5227xxcopuxqx2e7q foreign key (lkm_cust_id) references cst_customer (cust_id)
Hibernate: insert into cst_customer (cust_address, cust_industry, cust_level, cust_name, cust_phone, cust_source) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into cst_linkman (lkm_cust_id, lkm_email, lkm_gender, lkm_memo, lkm_mobile, lkm_name, lkm_phone, lkm_position) values (?, ?, ?, ?, ?, ?, ?, ?)
2 配置了客户到联系人的关系:
@SuppressWarnings("All")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class One2ManyTest {
    
    

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private LinkManDao linkManDao;

    /**
     * 保存一个客户,保存一个联系人
     */
    @Test
    @Transactional  // 配置事务
    @Rollback(value = false)  // 设置不自动回滚
    public void testAdd() {
    
    
        Customer customer = new Customer();
        customer.setCustName("测试");
        customer.setCustLevel("重要");
        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("one fine");
        /*
            配置了客户到联系人的关系:
                从客户的角度上,发送两条insert语句,发送一条更新语句更新数据库(更新外键)
                    由于配置了客户到联系人的关系:客户可以对外键进行维护
         */
        customer.getLinkMans().add(linkMan);

        customerDao.save(customer);
        linkManDao.save(linkMan);
    }

}

效果:

Hibernate: alter table cst_linkman drop foreign key FKh9yp1nql5227xxcopuxqx2e7q
Hibernate: drop table if exists cst_customer
Hibernate: drop table if exists cst_linkman
Hibernate: create table cst_customer (cust_id bigint not null auto_increment, cust_address varchar(255), cust_industry varchar(255), cust_level varchar(255), cust_name varchar(255), cust_phone varchar(255), cust_source varchar(255), primary key (cust_id))
Hibernate: create table cst_linkman (lkm_id bigint not null auto_increment, lkm_email varchar(255), lkm_gender varchar(255), lkm_memo varchar(255), lkm_mobile varchar(255), lkm_name varchar(255), lkm_phone varchar(255), lkm_position varchar(255), lkm_cust_id bigint, primary key (lkm_id))
Hibernate: alter table cst_linkman add constraint FKh9yp1nql5227xxcopuxqx2e7q foreign key (lkm_cust_id) references cst_customer (cust_id)
Hibernate: insert into cst_customer (cust_address, cust_industry, cust_level, cust_name, cust_phone, cust_source) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into cst_linkman (lkm_cust_id, lkm_email, lkm_gender, lkm_memo, lkm_mobile, lkm_name, lkm_phone, lkm_position) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: update cst_linkman set lkm_cust_id=? where lkm_id=?
3 配置了联系人到客户的关系:
@SuppressWarnings("All")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class One2ManyTest {
    
    

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private LinkManDao linkManDao;

    /**
     * 保存一个客户,保存一个联系人
     */
    @Test
    @Transactional  // 配置事务
    @Rollback(value = false)  // 设置不自动回滚
    public void testAdd() {
    
    
        Customer customer = new Customer();
        customer.setCustName("测试");
        customer.setCustLevel("重要");
        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("one fine");
        /*
            配置联系人到客户的关系(多对一)
                只发送了两条insert语句:由于配置了联系人到客户的映射关系(多对一)
         */
        linkMan.setCustomer(customer);

        customerDao.save(customer);
        linkManDao.save(linkMan);
    }

}

效果:

Hibernate: alter table cst_linkman drop foreign key FKh9yp1nql5227xxcopuxqx2e7q
Hibernate: drop table if exists cst_customer
Hibernate: drop table if exists cst_linkman
Hibernate: create table cst_customer (cust_id bigint not null auto_increment, cust_address varchar(255), cust_industry varchar(255), cust_level varchar(255), cust_name varchar(255), cust_phone varchar(255), cust_source varchar(255), primary key (cust_id))
Hibernate: create table cst_linkman (lkm_id bigint not null auto_increment, lkm_email varchar(255), lkm_gender varchar(255), lkm_memo varchar(255), lkm_mobile varchar(255), lkm_name varchar(255), lkm_phone varchar(255), lkm_position varchar(255), lkm_cust_id bigint, primary key (lkm_id))
Hibernate: alter table cst_linkman add constraint FKh9yp1nql5227xxcopuxqx2e7q foreign key (lkm_cust_id) references cst_customer (cust_id)
Hibernate: insert into cst_customer (cust_address, cust_industry, cust_level, cust_name, cust_phone, cust_source) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into cst_linkman (lkm_cust_id, lkm_email, lkm_gender, lkm_memo, lkm_mobile, lkm_name, lkm_phone, lkm_position) values (?, ?, ?, ?, ?, ?, ?, ?)
4 双向绑定:
@SuppressWarnings("All")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class One2ManyTest {
    
    

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private LinkManDao linkManDao;

    /**
     * 保存一个客户,保存一个联系人
     */
    @Test
    @Transactional  // 配置事务
    @Rollback(value = false)  // 设置不自动回滚
    public void testAdd() {
    
    
        Customer customer = new Customer();
        customer.setCustName("测试");
        customer.setCustLevel("重要");
        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("one fine");

        /*
            由于一的一方可以维护外键,会发送一条多余update语句
                解决此问题,只需要在一的一方放弃维护权即可
                    @OneToMany(mappedBy = "customer")
         */
        customer.getLinkMans().add(linkMan);  // 发送一条update语句
        linkMan.setCustomer(customer);

        customerDao.save(customer);
        linkManDao.save(linkMan);
    }
}

直接执行:

在这里插入图片描述
这里踩了个坑:

在进行一对多配置后,在测试方法中尝试使用获取一方信息,结果出现了内存溢出的错误。

总结一下原因以及解决方案:

原因一:为了方便看信息,在两类中分别重写了 toString 方法,导致查询加载时两类在互相调用对方的toString,形成递归,造成内存溢出。
解决方案: 在 toString 方法中任意一方去除打印的对方信息。

原因二: 为了编写方便简洁,代码更加优雅,使用了 lombok 插件中的@Data以及@ToString注解来标注类,让 lombok 来代替生成 gettet/setter 以及 toString,但是 lombok 在生成时会出现循环比较两类中的 hashcode,导致内存溢出。
解决方案: 不要使用 lombok ,自己手写。

参考: https://blog.csdn.net/weixin_43464964/article/details/90669843

更改:src\main\java\top\onefine\domain\Customer.java

package top.onefine.domain;

import lombok.*;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * 1. 实体类和表的映射关系
 *      -@Eitity
 *      -@Table
 * 2. 类中属性和数据库表中字段的映射关系
 *      -@Id 主键
 *      -@GeneratedValue 主键生成策略
 *      -@Column
 */
@Entity
@Table(name = "cst_customer")
//@Data  // 使用@Getter和@Setter,但是要自己生成toString方法
@Getter
@Setter
@NoArgsConstructor
public class Customer {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;
    @Column(name = "cust_address")
    private String custAddress;
    @Column(name = "cust_industry")
    private String custIndustry;
    @Column(name = "cust_level")
    private String custLevel;
    @Column(name = "cust_name")
    private String custName;
    @Column(name = "cust_phone")
    private String custPhone;
    @Column(name = "cust_source")
    private String custSource;

    // 配置客户和联系人之间的关系(一对多关系)
    /*
        使用注解的形式配置多表关系:
            1. 声明关系
                - @OneToMany:配置一对多关系
                    targetEntity:对方对象的字节码对象
            2. 配置外键(或中间表)
                - @JoinColumn:配置外键
                    name:从表 外键字段名称
                    referencedColumnName:参照的 主表 的主键字段名称

        注:在客户实体类上(一的一方)添加了外键的配置,所以对于客户而言,也具备了维护外键的作用

     */
    @OneToMany(targetEntity = LinkMan.class)
    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    /*
        放弃外键维护权
            mappedBy: 对方配置关系的属性名称
                表示参照对方的属性来做
     */
//    @OneToMany(mappedBy = "customer")
    private Set<LinkMan> linkMans = new HashSet<>();

    // 一定要自己写,不要使用lombok提供的
    @Override
    public String toString() {
    
    
        return "Customer{" +
                "custId=" + custId +
                ", custAddress='" + custAddress + '\'' +
                ", custIndustry='" + custIndustry + '\'' +
                ", custLevel='" + custLevel + '\'' +
                ", custName='" + custName + '\'' +
                ", custPhone='" + custPhone + '\'' +
                ", custSource='" + custSource + '\'' +
                ", linkMans=" + linkMans +
                '}';
    }
}

重新执行,效果:

Hibernate: alter table cst_linkman drop foreign key FKh9yp1nql5227xxcopuxqx2e7q
Hibernate: drop table if exists cst_customer
Hibernate: drop table if exists cst_linkman
Hibernate: create table cst_customer (cust_id bigint not null auto_increment, cust_address varchar(255), cust_industry varchar(255), cust_level varchar(255), cust_name varchar(255), cust_phone varchar(255), cust_source varchar(255), primary key (cust_id))
Hibernate: create table cst_linkman (lkm_id bigint not null auto_increment, lkm_email varchar(255), lkm_gender varchar(255), lkm_memo varchar(255), lkm_mobile varchar(255), lkm_name varchar(255), lkm_phone varchar(255), lkm_position varchar(255), lkm_cust_id bigint, primary key (lkm_id))
Hibernate: alter table cst_linkman add constraint FKh9yp1nql5227xxcopuxqx2e7q foreign key (lkm_cust_id) references cst_customer (cust_id)
Hibernate: insert into cst_customer (cust_address, cust_industry, cust_level, cust_name, cust_phone, cust_source) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into cst_linkman (lkm_cust_id, lkm_email, lkm_gender, lkm_memo, lkm_mobile, lkm_name, lkm_phone, lkm_position) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: update cst_linkman set lkm_cust_id=? where lkm_id=?

通过保存的案例,我们可以发现在设置了双向关系之后,会发送两条insert语句,一条多余的update语句,那我们的解决是思路很简单,就是一的一方放弃维护权,在src\main\java\top\onefine\domain\Customer.java中:

	// 放弃外键维护权的配置将如下配置改为
//    @OneToMany(targetEntity = LinkMan.class)
//    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    /*
        放弃外键维护权
            mappedBy: 对方配置关系的属性名称
                表示参照对方的属性来做
     */
     // 设置为
    @OneToMany(mappedBy = "customer")
    private Set<LinkMan> linkMans = new HashSet<>();

重新执行效果:

Hibernate: alter table cst_linkman drop foreign key FKh9yp1nql5227xxcopuxqx2e7q
Hibernate: drop table if exists cst_customer
Hibernate: drop table if exists cst_linkman
Hibernate: create table cst_customer (cust_id bigint not null auto_increment, cust_address varchar(255), cust_industry varchar(255), cust_level varchar(255), cust_name varchar(255), cust_phone varchar(255), cust_source varchar(255), primary key (cust_id))
Hibernate: create table cst_linkman (lkm_id bigint not null auto_increment, lkm_email varchar(255), lkm_gender varchar(255), lkm_memo varchar(255), lkm_mobile varchar(255), lkm_name varchar(255), lkm_phone varchar(255), lkm_position varchar(255), lkm_cust_id bigint, primary key (lkm_id))
Hibernate: alter table cst_linkman add constraint FKh9yp1nql5227xxcopuxqx2e7q foreign key (lkm_cust_id) references cst_customer (cust_id)
Hibernate: insert into cst_customer (cust_address, cust_industry, cust_level, cust_name, cust_phone, cust_source) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into cst_linkman (lkm_cust_id, lkm_email, lkm_gender, lkm_memo, lkm_mobile, lkm_name, lkm_phone, lkm_position) values (?, ?, ?, ?, ?, ?, ?, ?)

3.5.2 删除

	@Autowired
	private CustomerDao customerDao;
	
	@Test
	@Transactional
	@Rollback(false)//设置为不回滚
	public void testDelete() {
    
    
		customerDao.delete(1l);
	}

删除操作的说明如下:

  • 删除从表数据:可以随时任意删除。

  • 删除主表数据:

    • 有从表数据
      1、在默认情况下,它会把外键字段置为null,然后删除主表数据。如果在数据库的表 结构上,外键字段有非空约束,默认情况就会报错了。
      2、如果配置了放弃维护关联关系的权利,则不能删除(与外键字段是否允许为null, 没有关系)因为在删除时,它根本不会去更新从表的外键字段了。
      3、如果还想删除,使用级联删除引用

    • 没有从表数据引用:随便删

在实际开发中,级联删除请慎用!(在一对多的情况下)

3.5.3 级联操作

级联操作:指操作一个对象同时操作它的关联对象。有级联删除、级联更新、级联添加…

  • 级联添加:保存客户的时候同时保存联系人
  • 级联删除:删除客户的时候同时删除此客户的所有联系人

使用方法:只需要在操作主体的实体类上添加级联属性——需要添加到多表映射关系的注解上,即注解上配置cascade(作用:配置级联)

注意区分操作主体

/**
 * cascade:配置级联操作
 * 		CascadeType.MERGE	级联更新
 * 		CascadeType.PERSIST	级联保存:
 * 		CascadeType.REFRESH 级联刷新:
 * 		CascadeType.REMOVE	级联删除:
 * 		CascadeType.ALL		包含以上所有
 */
@OneToMany(mappedBy="customer",cascade=CascadeType.ALL)
级联添加:

src\main\resources\applicationContext.xml中:

	<bean>
    	<property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

src\main\java\top\onefine\domain\Customer.java中:

	/*
        放弃外键维护权
            mappedBy: 对方配置关系的属性名称
                表示参照对方的属性来做

            cascade:配置级联操作,可以配置到设置多表的映射关系的注解上
            * 		CascadeType.MERGE	级联更新
            * 		CascadeType.PERSIST	级联保存:
            * 		CascadeType.REFRESH 级联刷新:
            * 		CascadeType.REMOVE	级联删除:
            * 		CascadeType.ALL		包含以上所有,推荐配置
     */
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    private Set<LinkMan> linkMans = new HashSet<>();
	// 级联添加:保存一个客户的同时,保存该客户的所有联系人
    // 需要在操作主体的实体类上,配置casacde属性
    @Test
    @Transactional  // 配置事务
    @Rollback(false)  // 不自动回滚
    public void testCascadeAdd() {
    
    
        Customer customer = new Customer();
        customer.setCustName("百度1");
        LinkMan linkMan1 = new LinkMan();
        linkMan1.setLkmName("小王1");
        LinkMan linkMan2 = new LinkMan();
        linkMan2.setLkmName("小王2");

        customer.getLinkMans().add(linkMan1);
        customer.getLinkMans().add(linkMan2);
        linkMan1.setCustomer(customer);
        linkMan2.setCustomer(customer);

        customerDao.save(customer);  // 操作的主体是Customer
    }

效果:

Hibernate: insert into cst_customer (cust_address, cust_industry, cust_level, cust_name, cust_phone, cust_source) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into cst_linkman (lkm_cust_id, lkm_email, lkm_gender, lkm_memo, lkm_mobile, lkm_name, lkm_phone, lkm_position) values (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into cst_linkman (lkm_cust_id, lkm_email, lkm_gender, lkm_memo, lkm_mobile, lkm_name, lkm_phone, lkm_position) values (?, ?, ?, ?, ?, ?, ?, ?)
级联删除:
	// 级联删除:删除2号客户(上个级联添加添加的数据)的同时,删除2号客户的所有联系人
    // 需要在操作主体的实体类上,配置casacde属性
    @Test
    @Transactional  // 配置事务
    @Rollback(false)  // 不自动回滚
    public void testCascadeRemove() {
    
    
        // 1. 查询客户
        Customer customer = customerDao.findOne(2L);
        // 2. 删除2号客户
        customerDao.delete(customer);
    }

效果:

Hibernate: select customer0_.cust_id as cust_id1_0_0_, customer0_.cust_address as cust_add2_0_0_, customer0_.cust_industry as cust_ind3_0_0_, customer0_.cust_level as cust_lev4_0_0_, customer0_.cust_name as cust_nam5_0_0_, customer0_.cust_phone as cust_pho6_0_0_, customer0_.cust_source as cust_sou7_0_0_ from cst_customer customer0_ where customer0_.cust_id=?
Hibernate: select linkmans0_.lkm_cust_id as lkm_cust9_1_0_, linkmans0_.lkm_id as lkm_id1_1_0_, linkmans0_.lkm_id as lkm_id1_1_1_, linkmans0_.lkm_cust_id as lkm_cust9_1_1_, linkmans0_.lkm_email as lkm_emai2_1_1_, linkmans0_.lkm_gender as lkm_gend3_1_1_, linkmans0_.lkm_memo as lkm_memo4_1_1_, linkmans0_.lkm_mobile as lkm_mobi5_1_1_, linkmans0_.lkm_name as lkm_name6_1_1_, linkmans0_.lkm_phone as lkm_phon7_1_1_, linkmans0_.lkm_position as lkm_posi8_1_1_ from cst_linkman linkmans0_ where linkmans0_.lkm_cust_id=?
Hibernate: delete from cst_linkman where lkm_id=?
Hibernate: delete from cst_linkman where lkm_id=?
Hibernate: delete from cst_customer where cust_id=?

四、JPA中的多对多

4.1 示例分析

采用的示例为用户和角色。

  • 用户:指的是咱们班的每一个同学。

  • 角色:指的是咱们班同学的身份信息。

比如A同学,它是我的学生,其中有个身份就是学生,还是家里的孩子,那么他还有个身份是子女。

同时B同学,它也具有学生和子女的身份。

那么任何一个同学都可能具有多个身份。同时学生这个身份可以被多个同学所具有。

所以我们说,用户和角色之间的关系是多对多。

分析步骤

1.明确表关系:多对多关系
2.确定表关系(描述 外键|中间表):中间间表
3.编写实体类,再实体类中描述表关系(包含关系)

  • 用户:包含角色的集合
  • 角色:包含用户的集合

4.配置映射关系

4.2 表关系建立

多对多的表关系建立靠的是中间表,其中用户表和中间表的关系是一对多,角色表和中间表的关系也是一对多,如下图所示:

在这里插入图片描述

4.3 实体类关系建立以及映射配置

一个用户可以具有多个角色,所以在用户实体类中应该包含多个角色的信息,代码如下:

package top.onefine.domain;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "sys_user")
@Getter
@Setter
public class User {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long userId;
    @Column(name = "user_name")
    private String userName;
    @Column(name = "user_age")
    private Integer age;

    // 配置用户到角色的多对多关系
    /**
     * 配置多对多的映射关系
     *      1. 声明表关系的配置
     *          @ ManyToMany(targetEntity = Role.class)  // 多对多
     *              targetEntity 代表对方的实体类字节码
     *      2. 配置中间表(包含两个外键)
     *           @ JoinTable
     *              name 配置中间表名称
     *             joinColumns的数组 配置当前对象在中间表的外键
     *                  @ JoinColumn
     *                      name外键名
     *                      referencedColumnName参照主表的主键名
     *             inverseJoinColumns的数组 配置对方对象在中间表的外键
     *                  @ JoinColumn
     *                      name外键名
     *                      referencedColumnName参照主表的主键名
     */
    @ManyToMany(targetEntity = Role.class)
    @JoinTable(name = "sys_user_role", // 配置中间表名称
            joinColumns = {
    
    @JoinColumn(name = "sys_user_id", referencedColumnName = "user_id")}, // 配置当前对象在中间表中的外键,name随便,referencedColumnName参照当前对象主键
            inverseJoinColumns = {
    
    @JoinColumn(name = "sys_role_id", referencedColumnName = "role_id")}  // 配置对方对象在中间表的外键,name随便,referencedColumnName参照当前对象主键
    )
    private Set<Role> roles = new HashSet<>();

    @Override
    public String toString() {
    
    
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", age=" + age +
                '}';
    }
}
package top.onefine.domain;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "sys_role")
@Getter
@Setter
public class Role {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "role_id")
    private Long roleId;
    @Column(name = "role_name")
    private String roleName;

    // 配置角色到用户的多对多关系
    @ManyToMany(targetEntity = User.class)  // 声明多对多的关系
    @JoinTable(name = "sys_user_role", // 配置中间表名称
            joinColumns = {
    
    @JoinColumn(name = "sys_role_id", referencedColumnName = "role_id")}, // 配置当前对象在中间表中的外键,name随便,referencedColumnName参照当前对象主键
            inverseJoinColumns = {
    
    @JoinColumn(name = "sys_user_id", referencedColumnName = "user_id")}  // 配置对方对象在中间表的外键,name随便,referencedColumnName参照当前对象主键
    )
    // 放弃主键维护权
//    @ManyToMany(mappedBy = "roles")
    private Set<User> users = new HashSet<>();

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

4.4 映射的注解说明

@ManyToMany
	作用:用于映射多对多关系
	属性:
		cascade:配置级联操作。
		fetch:配置是否采用延迟加载。
    	targetEntity:配置目标的实体类。映射多对多的时候不用写。

@JoinTable
    作用:针对中间表的配置
    属性:
    	nam:配置中间表的名称
    	joinColumns:中间表的外键字段关联当前实体类所对应表的主键字段			  			
    	inverseJoinColumn:中间表的外键字段关联对方表的主键字段
    	
@JoinColumn
    作用:用于定义主键字段和外键字段的对应关系。
    属性:
    	name:指定外键字段的名称
    	referencedColumnName:指定引用主表的主键字段名称
    	unique:是否唯一。默认值不唯一
    	nullable:是否允许为空。默认值允许。
    	insertable:是否允许插入。默认值允许。
    	updatable:是否允许更新。默认值允许。
    	columnDefinition:列的定义信息。

4.5 多对多的操作

4.5.1 保存

src\main\resources\applicationContext.xml中:

<bean>
	<property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>
</bean>

src\main\java\top\onefine\dao\UserDao.java:

package top.onefine.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import top.onefine.domain.User;

public interface UserDao extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
    
    
}

src\main\java\top\onefine\dao\RoleDao.java:

package top.onefine.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import top.onefine.domain.Role;

public interface RoleDao extends JpaRepository<Role, Long>, JpaSpecificationExecutor<Role> {
    
    
}
栗子1:
package top.onefine.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import top.onefine.dao.RoleDao;
import top.onefine.dao.UserDao;
import top.onefine.domain.Role;
import top.onefine.domain.User;

@SuppressWarnings("All")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Many2ManyTest {
    
    

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    // 保存一个用户,保存一个角色
    @Test
    @Transactional
    @Rollback(false)
    public void testAdd() {
    
    
        User user = new User();
        user.setUserName("one fine");
        Role role = new Role();
        role.setRoleName("Java 工程师");

        userDao.save(user);
        roleDao.save(role);
    }
}

结果:

Hibernate: alter table sys_user_role drop foreign key FK1ef5794xnbirtsnudta6p32on
Hibernate: alter table sys_user_role drop foreign key FKsbjvgfdwwy5rfbiag1bwh9x2b
Hibernate: drop table if exists sys_role
Hibernate: drop table if exists sys_user
Hibernate: drop table if exists sys_user_role
Hibernate: create table sys_role (role_id bigint not null auto_increment, role_name varchar(255), primary key (role_id))
Hibernate: create table sys_user (user_id bigint not null auto_increment, user_age integer, user_name varchar(255), primary key (user_id))
Hibernate: create table sys_user_role (sys_user_id bigint not null, sys_role_id bigint not null, primary key (sys_role_id, sys_user_id))
Hibernate: alter table sys_user_role add constraint FK1ef5794xnbirtsnudta6p32on foreign key (sys_role_id) references sys_role (role_id)
Hibernate: alter table sys_user_role add constraint FKsbjvgfdwwy5rfbiag1bwh9x2b foreign key (sys_user_id) references sys_user (user_id)
Hibernate: insert into sys_user (user_age, user_name) values (?, ?)
Hibernate: insert into sys_role (role_name) values (?)
栗子2:
	// 保存一个用户,保存一个角色
    @Test
    @Transactional
    @Rollback(false)
    public void testAdd() {
    
    
        User user = new User();
        user.setUserName("one fine");
        Role role = new Role();
        role.setRoleName("Java 工程师");

        // 配置用户到角色关系,可以对中间表中的数据进行维护
        user.getRoles().add(role);

        userDao.save(user);
        roleDao.save(role);
    }

结果:

Hibernate: alter table sys_user_role drop foreign key FK1ef5794xnbirtsnudta6p32on
Hibernate: alter table sys_user_role drop foreign key FKsbjvgfdwwy5rfbiag1bwh9x2b
Hibernate: drop table if exists sys_role
Hibernate: drop table if exists sys_user
Hibernate: drop table if exists sys_user_role
Hibernate: create table sys_role (role_id bigint not null auto_increment, role_name varchar(255), primary key (role_id))
Hibernate: create table sys_user (user_id bigint not null auto_increment, user_age integer, user_name varchar(255), primary key (user_id))
Hibernate: create table sys_user_role (sys_user_id bigint not null, sys_role_id bigint not null, primary key (sys_role_id, sys_user_id))
Hibernate: alter table sys_user_role add constraint FK1ef5794xnbirtsnudta6p32on foreign key (sys_role_id) references sys_role (role_id)
Hibernate: alter table sys_user_role add constraint FKsbjvgfdwwy5rfbiag1bwh9x2b foreign key (sys_user_id) references sys_user (user_id)
Hibernate: insert into sys_user (user_age, user_name) values (?, ?)
Hibernate: insert into sys_role (role_name) values (?)
Hibernate: insert into sys_user_role (sys_user_id, sys_role_id) values (?, ?)
栗子3:
	@Test
    @Transactional
    @Rollback(false)
    public void testAdd() {
    
    
        User user = new User();
        user.setUserName("one fine");
        Role role = new Role();
        role.setRoleName("Java 工程师");

        // 配置角色到用户关系,可以对中间表中的数据进行维护
        role.getUsers().add(user);

        userDao.save(user);
        roleDao.save(role);
    }

效果:

Hibernate: alter table sys_user_role drop foreign key FK1ef5794xnbirtsnudta6p32on
Hibernate: alter table sys_user_role drop foreign key FKsbjvgfdwwy5rfbiag1bwh9x2b
Hibernate: drop table if exists sys_role
Hibernate: drop table if exists sys_user
Hibernate: drop table if exists sys_user_role
Hibernate: create table sys_role (role_id bigint not null auto_increment, role_name varchar(255), primary key (role_id))
Hibernate: create table sys_user (user_id bigint not null auto_increment, user_age integer, user_name varchar(255), primary key (user_id))
Hibernate: create table sys_user_role (sys_user_id bigint not null, sys_role_id bigint not null, primary key (sys_role_id, sys_user_id))
Hibernate: alter table sys_user_role add constraint FK1ef5794xnbirtsnudta6p32on foreign key (sys_role_id) references sys_role (role_id)
Hibernate: alter table sys_user_role add constraint FKsbjvgfdwwy5rfbiag1bwh9x2b foreign key (sys_user_id) references sys_user (user_id)
Hibernate: insert into sys_user (user_age, user_name) values (?, ?)
Hibernate: insert into sys_role (role_name) values (?)
Hibernate: insert into sys_user_role (sys_role_id, sys_user_id) values (?, ?)
栗子4:
	// 保存一个用户,保存一个角色
    @Test
    @Transactional
    @Rollback(false)
    public void testAdd() {
    
    
        User user = new User();
        user.setUserName("one fine");
        Role role = new Role();
        role.setRoleName("Java 工程师");

        // 配置用户到角色关系,可以对中间表中的数据进行维护	1:1
        user.getRoles().add(role);

        // 配置角色到用户关系,可以对中间表中的数据进行维护	1:1
        role.getUsers().add(user);

        userDao.save(user);
        roleDao.save(role);
    }

执行抛出异常,主键冲突:

在这里插入图片描述
在这里插入图片描述

在多对多(保存)中,如果双向都设置关系,意味着双方都维护中间表,都会往中间表插入数据,中间表的2个字段又作为联合主键,所以报错,主键重复,解决保存失败的问题:只需要在任意一方放弃对中间表的维护权即可,推荐在被动的一方放弃,被选择的放弃,这里是角色被用户选择,所以角色放弃维护权,配置如下:

//    // 配置角色到用户的多对多关系
//    @ManyToMany(targetEntity = User.class)  // 声明多对多的关系
//    @JoinTable(name = "sys_user_role", // 配置中间表名称
//            joinColumns = {@JoinColumn(name = "sys_role_id", referencedColumnName = "role_id")}, // 配置当前对象在中间表中的外键,name随便,referencedColumnName参照当前对象主键
//            inverseJoinColumns = {@JoinColumn(name = "sys_user_id", referencedColumnName = "user_id")}  // 配置对方对象在中间表的外键,name随便,referencedColumnName参照当前对象主键
//    )
    // 放弃主键维护权,解决保存中主键冲突的问题
    @ManyToMany(mappedBy = "roles")
    private Set<User> users = new HashSet<>();

重新执行,效果:

Hibernate: alter table sys_user_role drop foreign key FK1ef5794xnbirtsnudta6p32on
Hibernate: alter table sys_user_role drop foreign key FKsbjvgfdwwy5rfbiag1bwh9x2b
Hibernate: drop table if exists sys_role
Hibernate: drop table if exists sys_user
Hibernate: drop table if exists sys_user_role
Hibernate: create table sys_role (role_id bigint not null auto_increment, role_name varchar(255), primary key (role_id))
Hibernate: create table sys_user (user_id bigint not null auto_increment, user_age integer, user_name varchar(255), primary key (user_id))
Hibernate: create table sys_user_role (sys_user_id bigint not null, sys_role_id bigint not null, primary key (sys_user_id, sys_role_id))
Hibernate: alter table sys_user_role add constraint FK1ef5794xnbirtsnudta6p32on foreign key (sys_role_id) references sys_role (role_id)
Hibernate: alter table sys_user_role add constraint FKsbjvgfdwwy5rfbiag1bwh9x2b foreign key (sys_user_id) references sys_user (user_id)
Hibernate: insert into sys_user (user_age, user_name) values (?, ?)
Hibernate: insert into sys_role (role_name) values (?)
Hibernate: insert into sys_user_role (sys_user_id, sys_role_id) values (?, ?)
栗子5,级联添加:

src\main\java\top\onefine\domain\User.java中:

	@ManyToMany(targetEntity = Role.class, cascade = CascadeType.ALL)
    @JoinTable(name = "sys_user_role", // 配置中间表名称
            joinColumns = {
    
    @JoinColumn(name = "sys_user_id", referencedColumnName = "user_id")}, // 配置当前对象在中间表中的外键,name随便,referencedColumnName参照当前对象主键
            inverseJoinColumns = {
    
    @JoinColumn(name = "sys_role_id", referencedColumnName = "role_id")}  // 配置对方对象在中间表的外键,name随便,referencedColumnName参照当前对象主键
    )
    private Set<Role> roles = new HashSet<>();

src\test\java\top\onefine\test\Many2ManyTest.java中:

	// 测试级联添加:保存一个用户的同时保存用户的关联角色
    @Test
    @Transactional
    @Rollback(false)
    public void testCasCadeAdd() {
    
    
        User user = new User();
        user.setUserName("one fine");
        Role role = new Role();
        role.setRoleName("Java 工程师");

        // 配置用户到角色关系,可以对中间表中的数据进行维护
        user.getRoles().add(role);

        // 配置角色到用户关系,可以对中间表中的数据进行维护
        role.getUsers().add(user);

        userDao.save(user);
    }

效果:

Hibernate: alter table sys_user_role drop foreign key FK1ef5794xnbirtsnudta6p32on
Hibernate: alter table sys_user_role drop foreign key FKsbjvgfdwwy5rfbiag1bwh9x2b
Hibernate: drop table if exists sys_role
Hibernate: drop table if exists sys_user
Hibernate: drop table if exists sys_user_role
Hibernate: create table sys_role (role_id bigint not null auto_increment, role_name varchar(255), primary key (role_id))
Hibernate: create table sys_user (user_id bigint not null auto_increment, user_age integer, user_name varchar(255), primary key (user_id))
Hibernate: create table sys_user_role (sys_user_id bigint not null, sys_role_id bigint not null, primary key (sys_user_id, sys_role_id))
Hibernate: alter table sys_user_role add constraint FK1ef5794xnbirtsnudta6p32on foreign key (sys_role_id) references sys_role (role_id)
Hibernate: alter table sys_user_role add constraint FKsbjvgfdwwy5rfbiag1bwh9x2b foreign key (sys_user_id) references sys_user (user_id)
Hibernate: insert into sys_user (user_age, user_name) values (?, ?)
Hibernate: insert into sys_role (role_name) values (?)
Hibernate: insert into sys_user_role (sys_user_id, sys_role_id) values (?, ?)

4.5.2 删除

src\main\resources\applicationContext.xml中:

<bean>
	<property name="jpaProperties">
	    <props>
	        <prop key="hibernate.hbm2ddl.auto">update</prop>
	    </props>
	</property>
</bean>
级联删除:
	// 测试级联删除:删除id为1的客户(上个栗子保存的数据),同时删除他的关联对象
	/**
	 * 删除操作
	 * 	在多对多的删除时,双向级联删除根本不能配置
	 * 禁用
	 *	如果配了的话,如果数据之间有相互引用关系,可能会清空所有数据
	 */
    @Test
    @Transactional
    @Rollback(false)
    public void testCasCadeRemove() {
    
    
        // 1. 查询客户1
        User user = userDao.findOne(1L);
        // 2. 删除客户1
        userDao.delete(user);
    }

效果:

Hibernate: select user0_.user_id as user_id1_1_0_, user0_.user_age as user_age2_1_0_, user0_.user_name as user_nam3_1_0_ from sys_user user0_ where user0_.user_id=?
Hibernate: select roles0_.sys_user_id as sys_user1_2_0_, roles0_.sys_role_id as sys_role2_2_0_, role1_.role_id as role_id1_0_1_, role1_.role_name as role_nam2_0_1_ from sys_user_role roles0_ inner join sys_role role1_ on roles0_.sys_role_id=role1_.role_id where roles0_.sys_user_id=?
Hibernate: delete from sys_user_role where sys_user_id=?
Hibernate: delete from sys_role where role_id=?
Hibernate: delete from sys_user where user_id=?

五、Spring Data JPA中的多表查询

5.1 对象导航查询

对象导航查询即通过一个对象,查询此对象关联的所有对象。

对象图导航检索方式是根据已经加载的对象,导航到他的关联对象。它利用类与类之间的关系来检索对象。例如:我们通过ID查询方式查出一个客户,可以调用Customer类中的getLinkMans()方法来获取该客户的所有联系人。对象导航查询的使用要求是:两个对象之间必须存在关联关系。

查询一个客户,获取该客户下的所有联系人

	@Autowired
	private CustomerDao customerDao;
	
	@Test
	//由于是在java代码中测试,为了解决no session问题,将操作配置到同一个事务中
	@Transactional 
	public void testFind() {
    
    
		Customer customer = customerDao.findOne(5l);
		Set<LinkMan> linkMans = customer.getLinkMans();//对象导航查询
		for(LinkMan linkMan : linkMans) {
    
    
  			System.out.println(linkMan);
		}
	}

查询一个联系人,获取该联系人的所有客户

	@Autowired
	private LinkManDao linkManDao;
	
	@Test
	public void testFind() {
    
    
		LinkMan linkMan = linkManDao.findOne(4l);
		Customer customer = linkMan.getCustomer(); //对象导航查询
		System.out.println(customer);
	}

对象导航查询的问题分析

问题1:我们查询客户时,要不要把联系人查询出来?

分析:如果我们不查的话,在用的时候还要自己写代码,调用方法去查询。如果我们查出来的,不使用时又会白白的浪费了服务器内存。

解决:采用延迟加载的思想。通过配置的方式来设定当我们在需要使用时,发起真正的查询。

配置方式:

	/**
	 * 在客户对象的@OneToMany注解中添加fetch属性
	 * 		FetchType.EAGER	:立即加载
	 * 		FetchType.LAZY	:延迟加载
	 */
	@OneToMany(mappedBy="customer",fetch=FetchType.EAGER)
	private Set<LinkMan> linkMans = new HashSet<>(0);

问题2:我们查询联系人时,要不要把客户查询出来?

分析:例如:查询联系人详情时,肯定会看看该联系人的所属客户。如果我们不查的话,在用的时候还要自己写代码,调用方法去查询。如果我们查出来的话,一个对象不会消耗太多的内存。而且多数情况下我们都是要使用的。

解决: 采用立即加载的思想。通过配置的方式来设定,只要查询从表实体,就把主表实体对象同时查出来

配置方式

	/**
	 * 在联系人对象的@ManyToOne注解中添加fetch属性
	 * 		FetchType.EAGER	:立即加载
	 * 		FetchType.LAZY	:延迟加载
	 */
	@ManyToOne(targetEntity=Customer.class,fetch=FetchType.EAGER)
	@JoinColumn(name="cst_lkm_id",referencedColumnName="cust_id")
	private Customer customer;

栗子,使用第三章(一对多)的配置

src\main\java\top\onefine\domain\Customer.java:

package top.onefine.domain;

import lombok.*;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * 1. 实体类和表的映射关系
 *      -@Eitity
 *      -@Table
 * 2. 类中属性和数据库表中字段的映射关系
 *      -@Id 主键
 *      -@GeneratedValue 主键生成策略
 *      -@Column
 */
@Entity
@Table(name = "cst_customer")
@Getter
@Setter
@NoArgsConstructor
public class Customer {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;
    @Column(name = "cust_address")
    private String custAddress;
    @Column(name = "cust_industry")
    private String custIndustry;
    @Column(name = "cust_level")
    private String custLevel;
    @Column(name = "cust_name")
    private String custName;
    @Column(name = "cust_phone")
    private String custPhone;
    @Column(name = "cust_source")
    private String custSource;

    // 配置客户和联系人之间的关系(一对多关系)
    /*
        使用注解的形式配置多表关系:
            1. 声明关系
                - @OneToMany:配置一对多关系
                    targetEntity:对方对象的字节码对象
            2. 配置外键(或中间表)
                - @JoinColumn:配置外键
                    name:从表 外键字段名称
                    referencedColumnName:参照的 主表 的主键字段名称

        注:在客户实体类上(一的一方)添加了外键的配置,所以对于客户而言,也具备了维护外键的作用

     */
//    @OneToMany(targetEntity = LinkMan.class)
//    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    /*
        放弃外键维护权
            mappedBy: 对方配置关系的属性名称
                表示参照对方的属性来做

            cascade:配置级联操作,可以配置到设置多表的映射关系的注解上
            * 		CascadeType.MERGE	级联更新
            * 		CascadeType.PERSIST	级联保存:
            * 		CascadeType.REFRESH 级联刷新:
            * 		CascadeType.REMOVE	级联删除:
            * 		CascadeType.ALL		包含以上所有,推荐配置


            fetch:配置关联对象的加载方式
                FetchType.EAGER 立即加载 -- 不推荐
                FetchType.LAZY  延迟加载 -- 默认
     */
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL/*, fetch = FetchType.EAGER*/)
    private Set<LinkMan> linkMans = new HashSet<>();

    // 注意不含集合
    @Override
    public String toString() {
    
    
        return "Customer{" +
                "custId=" + custId +
                ", custAddress='" + custAddress + '\'' +
                ", custIndustry='" + custIndustry + '\'' +
                ", custLevel='" + custLevel + '\'' +
                ", custName='" + custName + '\'' +
                ", custPhone='" + custPhone + '\'' +
                ", custSource='" + custSource + '\'' +
                '}';
    }
}

src\main\java\top\onefine\domain\LinkMan.java:

package top.onefine.domain;

import lombok.*;

import javax.persistence.*;

@Entity
@Table(name = "cst_linkman")
//@Data
@Getter
@Setter
//@ToString
@NoArgsConstructor
public class LinkMan {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "lkm_id")
    private Long lkmId;  // 联系人编号
    @Column(name = "lkm_name")
    private String lkmName;  // 联系人姓名
    @Column(name = "lkm_gender")
    private String lkmGender;  // 联系人性别  // 对应数据库表中字段char(1)
    @Column(name = "lkm_phone")
    private String lkmPhone;  // 联系人办公电话
    @Column(name = "lkm_mobile")
    private String lkmMobile;  // 联系人手机
    @Column(name = "lkm_email")
    private String lkmEmail;  // 联系人邮箱
    @Column(name = "lkm_position")
    private String lkmPosition;  // 联系人职位
    @Column(name = "lkm_memo")
    private String lkmMemo;  // 联系人备注

    // 配置联系人到客户的多对一关系
    /*
        使用注解的形式配置多对一关系
            1. 配置表关系
                - @ManyToOne:配置多对一关系
                    targetEntity:对方对象的字节码对象
            2. 配置外键(或中间表)

        注:配置外键的过程,配置到了多的一方,就会在多的一方维护外键

        fetch:配置关联对象的加载方式
                FetchType.EAGER 立即加载 -- 默认
                FetchType.LAZY  延迟加载
     */
    @ManyToOne(targetEntity = Customer.class/*, fetch = FetchType.LAZY*/)
    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    private Customer customer;

    // 注意不含customer
    @Override
    public String toString() {
    
    
        return "LinkMan{" +
                "lkmId=" + lkmId +
                ", lkmName='" + lkmName + '\'' +
                ", lkmGender='" + lkmGender + '\'' +
                ", lkmPhone='" + lkmPhone + '\'' +
                ", lkmMobile='" + lkmMobile + '\'' +
                ", lkmEmail='" + lkmEmail + '\'' +
                ", lkmPosition='" + lkmPosition + '\'' +
                ", lkmMemo='" + lkmMemo + '\'' +
                '}';
    }
}

src\test\java\top\onefine\dao\ObjectQueryTest.java:

package top.onefine.dao;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import top.onefine.domain.Customer;
import top.onefine.domain.LinkMan;

import java.util.Set;


@SuppressWarnings("All")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class ObjectQueryTest {
    
    

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private LinkManDao linkManDao;

    @Test
    @Transactional  // 解决:could not initialize proxy - no Session 问题
    public void testQuery1() {
    
    
        // 1. 查询客户
        Customer user = customerDao.getOne(3L);  // 延迟加载
        // 2. 对象导航查询,查询此客户下的所有联系人
        Set<LinkMan> linkMans = user.getLinkMans();
        for (LinkMan linkMan : linkMans) {
    
    
            System.out.println(linkMan);
        }
    }

    /**
     * 一的一方
     * 注意:对象导航查询 默认使用的是延迟加载 的形式查询的
     *      调用getLinkMans方法并不会立即发送查询,而是在使用关联对象的时候才会查询,所以是延迟加载!
     *
     * 若需要将延迟加载改为立即加载(不推荐使用),需要修改配置 Customer中设置
     *      fetch,需要配置到多表映射关系的注解上
     */
    @Test
    @Transactional  // 解决:could not initialize proxy - no Session 问题
    public void testQuery2() {
    
    
        // 1. 查询客户
        Customer user = customerDao.findOne(3L);  // 立即加载
        // 2. 对象导航查询,查询此客户下的所有联系人
        Set<LinkMan> linkMans = user.getLinkMans();
//        System.out.println(linkMans.size());
        System.out.println(linkMans);
    }

    // 从联系人对象导航查询所属客户
    /** 多的一方
     * 注意:对象导航查询 默认使用的是立即加载 的形式查询的
     *      调用getCustomer方法会立即发送查询
     *
     * 若需要将延迟加载改为立即加载(不推荐使用),需要修改配置 LinkMan中设置
     *      fetch,需要配置到多表映射关系的注解上
     */
    @Test
    @Transactional  // 解决:could not initialize proxy - no Session 问题
    public void testQuery3() {
    
    
        // 1. 查询联系人
        LinkMan linkMan = linkManDao.findOne(4L);
        assert linkMan != null;
        // 2. 对象导航查询,查询此联系人对应的客户
        Customer customer = linkMan.getCustomer();

        System.out.println(customer);
    }
}

其他不变,参照第三章:
src\main\java\top\onefine\dao\CustomerDao.java
src\main\java\top\onefine\dao\LinkManDao.java
src\main\resources\applicationContext.xml
pom.xml

总结:

对象导航查询:查询一个对象的同时,通过此对象查询他的关联对象

  • 从一方查询多方;默认:使用延迟加载,务必

  • 从多方查询一方;默认:使用立即加载

5.2 使用Specification查询

	/**
	 * Specification的多表查询
	 */
	@Test
	public void testFind() {
    
    
		Specification<LinkMan> spec = new Specification<LinkMan>() {
    
    
			public Predicate toPredicate(Root<LinkMan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    
    
				//Join代表链接查询,通过root对象获取
				//创建的过程中,第一个参数为关联对象的属性名称,第二个参数为连接查询的方式(left,inner,right)
				//JoinType.LEFT : 左外连接,JoinType.INNER:内连接,JoinType.RIGHT:右外连接
				Join<LinkMan, Customer> join = root.join("customer",JoinType.INNER);
				return cb.like(join.get("custName").as(String.class),"传智播客1");
			}
		};
		List<LinkMan> list = linkManDao.findAll(spec);
		for (LinkMan linkMan : list) {
    
    
			System.out.println(linkMan);
		}
	}

猜你喜欢

转载自blog.csdn.net/jiduochou963/article/details/105549789