Spring Data Jpa多表关系

一、一对多与多对一

1、数据表(无需创建,下方使用自动创建)

/*创建客户表*/
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;

2、建立表和实体间的映射关系

配置客户与联系人之间的关系(一个客户对应多个联系人) 使用注解的形式配置多表关系

  1. 声明关系

    @OnetoMany:配置一对多关系

    targetEntity:对方对象的字节码对象

  2. 配置外键(中间表)

    @JoinColumn

    name:外键的在从表的字段名称(不是属性,是数据库的字段名称)

    referencedColumnName:参照的主表的字段名称

@Entity
@Table(name = "cst_customer")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;
    @Column(name = "cust_name")
    private String custName;
    @Column(name = "cust_source")
    private String custSource;

    @Column(name = "cust_industry")
    private String custIndustry;
    @Column(name = "cust_level")
    private String custLevel;
    @Column(name = "cust_address")
    private String custAddress;
    @Column(name = "cust_phone")
    private String custPhone;
    
    @OneToMany(targetEntity = LinkMan.class)
    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    private Set<LinkMan> linkManSet = new HashSet<>();
    /*getter、setter、toString(不要用Lombok!有可能会栈溢出)*/
}

 

配置联系人到客户的多对一关系 外键字段是设置在从表中的,且该字段并未作为对象的属性去配置,而实作为外键去配置

使用注解的形式配置多对一关系

  1. 配置表关系

    @ManyToOne:配置多对一关系

    targetEntity:对方的实体类字节码

  2. 配置外键(中间表)

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

@Entity
@Table(name="cst_linkman")
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;
    @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;

    @ManyToOne(targetEntity = Customer.class)
    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    private Customer customer;
    /*getter、setter、toString(不要用Lombok!有可能会栈溢出)*/
}

3、编写持久层接口

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

4、配置

<?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的配置-->
    <!--配置包扫描-->
    <context:component-scan base-package="com.linyh"/>
    <!--1.配置数据库连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl"
                  value="jdbc:mysql://localhost:3306/spring data jpa?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
        <property name="user" value="root"/>
        <property name="password" value="LYH2277904016.."/>
    </bean>

    <!--2.配置entityManageFactory对象交给spring容器管理  指定实体类所在的包名称-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--i 配置的是扫描的包(实体类所在的包)-->
        <property name="packagesToScan" value="com.linyh.entity"/>
        <!--ii 配置Jpa的实现厂家-->
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
        </property>
        <!--iii 配置JPA的供应商适配器-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--配置是否自动创建数据库表-->
                <property name="generateDdl" value="true"/>
                <!--指定数据库类型,注意全部是大写-->
                <property name="database" value="MYSQL"/>
                <!--数据库方言:支持的特有语法(每个数据库都有细微的差别)-->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
                <property name="showSql" value="true"/>
            </bean>
        </property>
        <!--配置Jpa的方言:高级的特性,不同的实现厂商有各自的特性,比如Hibernate-->
        <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.show_sql">true</prop>-->
<!--                <prop key="hibernate.format_sql">false</prop>-->
<!--                <prop key="hibernate.hbm2dd1.auto">create</prop>-->
<!--                <prop key="hibernate.connection.charSet">UTF-8</prop>-->
<!--                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>-->
<!--            </props>-->
<!--        </property>-->

    </bean>
    <!-- 3.JPA事务管理器  -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <!--4.整合Spring Data Jpa   指定dao接口的包名称 声明要对此包下的dao接口进行动态代理增强,生成simpleJpaRepository代理类-->
    <jpa:repositories base-package="com.linyh.dao" transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory"/>

<!--    &lt;!&ndash;5.txAdvice&ndash;&gt;-->
<!--    <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>-->

<!--    &lt;!&ndash; 6.aop&ndash;&gt;-->
<!--    <aop:config>-->
<!--        <aop:pointcut id="pointcut" expression="execution(* com.linyh.service.*.*(..))"/>-->
<!--        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>-->
<!--    </aop:config>-->
</beans>
View Code

5、依赖

    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
        <hibernate.version>5.0.7.Final</hibernate.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <c3p0.version>0.9.1.2</c3p0.version>
        <mysql.version>5.1.6</mysql.version>
    </properties>

    <dependencies>
        <!-- junit单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- spring beg -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--是spring对orm相关支持的包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- spring end -->

        <!-- hibernate beg -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.4.1.Final</version>
        </dependency>
        <!-- hibernate end -->

        <!-- c3p0 beg -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>
        <!-- c3p0 end -->

        <!-- log end -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!--springdatajpa的坐标-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.9.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- el beg 使用spring data jpa 必须引入 -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>
        <!-- el end -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <!--json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>
    </dependencies>
View Code

 6、新增

方式一(使用一的一方维护外键):

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:ApplicationContext.xml")
public class MyTest {
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private LinkManDao linkManDao;

    @Test
    @Transactional
    @Rollback(value = false)
    public void save1() {
        Customer customer = new Customer();
        customer.setCustName("AAA");
        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("BBB");

        customer.getLinkManSet().add(linkMan);

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

 update语句是由于下面语句产生的:

customer.getLinkManSet().add(linkMan);

可使用以下方式放弃外键维护:

@OneToMany(mappedBy = "customer")                 
private Set<LinkMan> linkManSet = new HashSet<>();

方式二(使用多的一方维护外键):

@Test                                   
@Transactional                          
@Rollback(value = false)                
public void save2() {                   
    Customer customer = new Customer(); 
    customer.setCustName("AAA");        
    LinkMan linkMan = new LinkMan();    
    linkMan.setLkmName("BBB");          
                                        
    linkMan.setCustomer(customer);      
                                        
    customerDao.save(customer);         
    linkManDao.save(linkMan);           
}                                       

使用linkMan.setCustomer(customer);不会生成update语句,直接对外键赋值

7、级联

有从表数据

  • 在默认情况下,它会把外键字段置为null,然后删除主表数据。如果在数据库的表结构上,外键字段有非空约束,默认情况就会报错。

  • 如果配置了放弃维护关联关系的权利,则不能删除(与外键字段是否允许为null没有关系)因为在删除时,要现判断是否有外键,但是此时放弃维护外键,是否有外键成了未知。

  • 如果还想删除,使用级联删除引用

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

操作一个对象的同时操作他的关联对象
级联操作:
1.需要区分操作主体
2.需要在操作主体的实体类上,添加级联属性(需要添加到多表映射关系的注解上)
3.cascade(配置级联)

级联添加,
案例:当我保存一个客户的同时保存联系人
级联删除
案例:当我删除一个客户的同时删除此客户的所有联系人

级联添加(方式1):

@Entity
@Table(name="cst_linkman")
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;
    @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;

    @ManyToOne(targetEntity = Customer.class)
    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    private Customer customer;
    /*getter、setter、toString(不要用Lombok!有可能会栈溢出)*/
}
@Entity
@Table(name = "cst_customer")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;
    @Column(name = "cust_name")
    private String custName;
    @Column(name = "cust_source")
    private String custSource;

    @Column(name = "cust_industry")
    private String custIndustry;
    @Column(name = "cust_level")
    private String custLevel;
    @Column(name = "cust_address")
    private String custAddress;
    @Column(name = "cust_phone")
    private String custPhone;

    // ALL代表级联删除+添加
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    private Set<LinkMan> linkManSet = new HashSet<>();
    /*getter, setter, toString*/
}
@Test                                     
@Transactional                            
@Rollback(value = false)                  
public void cascadeSave() {               
    Customer customer = new Customer();   
    customer.setCustName("AAA");          
    LinkMan linkMan = new LinkMan();      
    linkMan.setLkmName("BBB");            
                                          
    customer.getLinkManSet().add(linkMan);
    //注意此处添加                              
    linkMan.setCustomer(customer);        
                                          
    customerDao.save(customer);           
}                                         

级联删除:

@Test                                             
@Transactional                                    
@Rollback(value = false)                          
public void cascadeDelete() {                     
    Customer cutomer = customerDao.findOne(4L);   
    customerDao.delete(cutomer);                  
}                                                 

级联添加(方式2):

@Entity
@Table(name = "cst_customer")
@Getter
@Setter
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;
    @Column(name = "cust_name")
    private String custName;
    @Column(name = "cust_source")
    private String custSource;

    @Column(name = "cust_industry")
    private String custIndustry;
    @Column(name = "cust_level")
    private String custLevel;
    @Column(name = "cust_address")
    private String custAddress;
    @Column(name = "cust_phone")
    private String custPhone;

    @OneToMany(targetEntity = LinkMan.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    private Set<LinkMan> linkManSet = new HashSet<>();

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName='" + custName + '\'' +
                ", custSource='" + custSource + '\'' +
                ", custIndustry='" + custIndustry + '\'' +
                ", custLevel='" + custLevel + '\'' +
                ", custAddress='" + custAddress + '\'' +
                ", custPhone='" + custPhone + '\'' +
                ", linkManSet=" + linkManSet +
                '}';
    }
}
@Entity
@Table(name="cst_linkman")
@Getter
@Setter
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;
    @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;

//    @ManyToOne(targetEntity = Customer.class, cascade = CascadeType.ALL)
//    @JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")
    @ManyToOne
    private Customer customer;

    @Override
    public String toString() {
        return "LinkMan{" +
                "lkmId=" + lkmId +
                ", lkmName='" + lkmName + '\'' +
                ", lkmGender='" + lkmGender + '\'' +
                ", lkmPhone='" + lkmPhone + '\'' +
                ", lkmMobile='" + lkmMobile + '\'' +
                ", lkmEmail='" + lkmEmail + '\'' +
                ", lkmPosition='" + lkmPosition + '\'' +
                ", lkmMemo='" + lkmMemo + '\'' +
                ", customer=" + customer +
                '}';
    }
}
@Test                                     
@Transactional                            
@Rollback(value = false)                  
public void cascadeSave() {               
    Customer customer = new Customer();   
    customer.setCustName("AAA");          
    LinkMan linkMan = new LinkMan();      
    linkMan.setLkmName("BBB");            
                                          
    customer.getLinkManSet().add(linkMan);      
    customerDao.save(customer);           
}                                         

8、查询(对象导航查询)

客户表:

 

 

 联系人表:

 

 

 查询一个对象时,通过关联关系获取所有关联对象:

@Test                                                            
@Transactional                                                   
@Rollback(value = false)                                         
public void query1() {                                           
    // 获取指定id对象                                                  
    Customer customer = customerDao.findOne(1L);                 
    System.out.println(customer);                                
    Set<LinkMan> linkManSet = customer.getLinkManSet();          
    linkManSet.forEach((linkMan)-> System.out.println(linkMan)); 
}                                                                

其中Set<LinkMan> linkManSet = customer.getLinkManSet(); 默认采用的是延迟加载方式,也就是说使用到linkManSet时才会查询

可以在注解中使用fetch配置是否延迟加载(fetch设置的是获取对应方时是否采用延迟加载):

@OneToMany(targetEntity = LinkMan.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) 
@JoinColumn(name = "lkm_cust_id", referencedColumnName = "cust_id")                          
private Set<LinkMan> linkManSet = new HashSet<>();                                           

如果选择立即加载,那么在查询customer时顺便查了其包含的linkMan,类似下方sql语句:

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_,
  linkmanset1_.lkm_cust_id AS lkm_cus10_1_1_,
  linkmanset1_.lkm_id AS lkm_id1_1_1_,
  linkmanset1_.lkm_id AS lkm_id1_1_2_,
  linkmanset1_.customer_cust_id AS customer9_1_2_,
  linkmanset1_.lkm_email AS lkm_emai2_1_2_,
  linkmanset1_.lkm_gender AS lkm_gend3_1_2_,
  linkmanset1_.lkm_memo AS lkm_memo4_1_2_,
  linkmanset1_.lkm_mobile AS lkm_mobi5_1_2_,
  linkmanset1_.lkm_name AS lkm_name6_1_2_,
  linkmanset1_.lkm_phone AS lkm_phon7_1_2_,
  linkmanset1_.lkm_position AS lkm_posi8_1_2_,
  customer2_.cust_id AS cust_id1_0_3_,
  customer2_.cust_address AS cust_add2_0_3_,
  customer2_.cust_industry AS cust_ind3_0_3_,
  customer2_.cust_level AS cust_lev4_0_3_,
  customer2_.cust_name AS cust_nam5_0_3_,
  customer2_.cust_phone AS cust_pho6_0_3_,
  customer2_.cust_source AS cust_sou7_0_3_
FROM
  cst_customer customer0_
  LEFT OUTER JOIN cst_linkman linkmanset1_
    ON customer0_.cust_id = linkmanset1_.lkm_cust_id
  LEFT OUTER JOIN cst_customer customer2_
    ON linkmanset1_.customer_cust_id = customer2_.cust_id
WHERE customer0_.cust_id = ?

通过多的一方查询一的一方:

@Test                                           
@Transactional                                  
public void query2() {                          
    LinkMan linkMan = linkManDao.findOne(2L);   
    Customer customer = linkMan.getCustomer();  
    System.out.println(customer);               
}                                               

默认立即加载。

二、多对多关系

 1、建立表和实体间的映射关系

@Entity
@Table(name="sys_user")
@Getter
@Setter
public class SysUser implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="user_id")
    private Long userId;
    @Column(name="user_code")
    private String userCode;
    @Column(name="user_name")
    private String userName;
    @Column(name="user_password")
    private String userPassword;
    @Column(name="user_state")
    private String userState;

    //多对多关系映射
    @ManyToMany(mappedBy="users")
    private Set<SysRole> roles = new HashSet<SysRole>(0);

    @Override
    public String toString() {
        return "SysUser [userId=" + userId + ", userCode=" + userCode + ", userName=" + userName + ", userPassword="
                + userPassword + ", userState=" + userState + "]";
    }
}
@Entity
@Table(name="sys_role")
@Getter
@Setter
public class SysRole implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="role_id")
    private Long roleId;
    @Column(name="role_name")
    private String roleName;
    @Column(name="role_memo")
    private String roleMemo;

    //多对多关系映射
    @ManyToMany
    @JoinTable(name="user_role_rel",//中间表的名称
            //中间表user_role_rel字段关联sys_role表的主键字段role_id
            joinColumns={@JoinColumn(name="role_id",referencedColumnName="role_id")},
            //中间表user_role_rel的字段关联sys_user表的主键user_id
            inverseJoinColumns={@JoinColumn(name="user_id",referencedColumnName="user_id")}
    )
    private Set<SysUser> users = new HashSet<SysUser>(0);

    @Override
    public String toString() {
        return "SysRole [roleId=" + roleId + ", roleName=" + roleName + ", roleMemo=" + roleMemo + "]";
    }
}

2、持久层接口

public interface SysUserDao extends JpaRepository<SysUser, Long>, JpaSpecificationExecutor<SysUser> {
}
public interface SysRoleDao extends JpaRepository<SysRole, Long>, JpaSpecificationExecutor<SysRole> {
}

3、测试

@Test                                   
@Transactional                          
@Rollback(value = false)                
public void save() {                   
    SysUser user = new SysUser();       
    user.setUserName("张三");             
    SysRole role = new SysRole();       
    role.setRoleName("李四");             
                                        
    // 该语句会将role表记录的id和user表记录的id赋值给中间表 
    role.getUsers().add(user);          
                                        
    sysUserDao.save(user);              
    sysRoleDao.save(role);              
}                                       

 4、级联

修改SysRole表:

@Entity
@Table(name="sys_role")
@Getter
@Setter
public class SysRole implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="role_id")
    private Long roleId;
    @Column(name="role_name")
    private String roleName;
    @Column(name="role_memo")
    private String roleMemo;

    //多对多关系映射
    @ManyToMany(targetEntity = SysUser.class, cascade = CascadeType.ALL)
    @JoinTable(name="user_role_rel",//中间表的名称
            //中间表user_role_rel字段关联sys_role表的主键字段role_id
            joinColumns={@JoinColumn(name="role_id",referencedColumnName="role_id")},
            //中间表user_role_rel的字段关联sys_user表的主键user_id
            inverseJoinColumns={@JoinColumn(name="user_id",referencedColumnName="user_id")}
    )
    private Set<SysUser> users = new HashSet<SysUser>(0);

    @Override
    public String toString() {
        return "SysRole [roleId=" + roleId + ", roleName=" + roleName + ", roleMemo=" + roleMemo + "]";
    }
}

增加:

@Test                                   
@Transactional                          
@Rollback(value = false)                
public void cascadeSave() {             
    SysUser user = new SysUser();       
    user.setUserName("小明");             
    SysRole role = new SysRole();       
    role.setRoleName("王五");             
                                        
    // 该语句会将role表记录的id和user表记录的id赋值给中间表 
    role.getUsers().add(user);          
                                        
    sysRoleDao.save(role);              
}                                       

 删除:

@Test                                       
@Transactional                              
@Rollback(value = false)                    
public void cascadeDelete() {               
    SysRole role = sysRoleDao.findOne(3L);  
    sysRoleDao.delete(role);                
}                                           

三、映射注解说明

@OneToMany:

作用:建立一对多的关系映射

属性:

- targetEntityClass:指定多的多方的类的字节码
- mappedBy:指定从表实体类中引用主表对象的名称。
- cascade:指定要使用的级联操作
- fetch:指定是否采用延迟加载
- orphanRemoval:是否使用孤儿删除

 

@ManyToOne

作用:建立多对一的关系

属性:

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

 

@JoinColumn

作用:用于定义主键字段和外键字段的对应关系。

属性:

- name:指定外键字段的名称
- referencedColumnName:指定引用主表的主键字段名称
- unique:是否唯一。默认值不唯一
- nullable:是否允许为空。默认值允许。
- insertable:是否允许插入。默认值允许。
- updatable:是否允许更新。默认值允许。
- columnDefinition:列的定义信息。

 

参考:https://juejin.cn/post/6844904160807092237#heading-17

posted @ 2021-01-23 00:12  yhliln  阅读(149)  评论(0编辑  收藏  举报