Loading

Spring Data Jpa (三)

多表之间的关系和操作多表的操作步骤

  • 表关系

    • 一对一

    • 一对多

      • 一的一方: 主表
      • 多的一方:从表
      • 外键:需要在从表上新建一列作为外键,他的取值来源于主表的主键
    • 多对多:

      • 中间表:中间表中最少应该有两个字段组成,这两个字段做为外键指向两张表的主键,又组成了联合表

      讲师对学员: 一对多关系

  • 实体类中的关系

    • 包含关系:可以通过实体类中的包含关系描述表关系
    • 继承关系:
  • 分析步骤

    • 1、明确表关系
    • 2、确定表关系(描述 外键 | 中间表)
    • 3、编写实体类,在实体类中描述表关系(包含关系)
    • 4、配置映射关系

一对多操作

案例 : 客户和联系人的案例 (一对多)

​ 客户 : 可以看做是一家公司

​ 联系人 : 这家公司的员工

一个客户可以具有多个联系人

一个联系人从属一家公司

分析步骤

  • 1、明确表关系
    • 一对多的关系
  • 2、确定表关系(描述 外键 | 中间表)
    • 主表 : 客户表
    • 从表 : 联系人表
      • 再从表上添加外键
  • 3、编写实体类,在实体类中描述表关系(包含关系)
    • 客户 : 在客户的实体类中包含一个联系人的集合
    • 联系人 : 在联系人的实体类中包含一个客户的对象
  • 4、配置映射关系
    • 使用jpa注解配置一对多映射关系

完成多表操作

环境搭建

配置OneToMany:一对多关系
targetEntity:对方对象的字节码对象
cascade = CascadeType.ALL:级联添加:保存一个客户的同时,保存客户的所有联系人

@ManyToOne:配置多对一关系
referencedColumnName:对方的实体类字节码

Customer

@Entity
@Table(name = "cst_customer")
public class Customer {
    /**
     * @Id:声明主键配置
     * @GeneratedValue:配置主键的生成策略
     *          GenerationType.IDENTITY:自增
     * @Column:配置属性和字段的映射关系
     *      name:数据库表中字段的名称
     */
    @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_level")
    private String custLevel;//客户级别
    @Column(name = "cust_industry")
    private String custIndustry;//客户所属行业
    @Column(name = "cust_phone")
    private String custPhone;//客户的联系方式
    @Column(name = "cust_address")
    private String custAddress;//客户地址


    //配置客户和联系人之间的关系(一对多关系)
    /**
     * 使用注解的形式配置多表关系
     *      1.声明关系  :
     *          配置OneToMany:一对多关系
     *                  targetEntity:对方对象的字节码对象
     *      2.配置外键(中间表)
     *              @JoinColumn:配置外键
     *                      name:外键字段名称
     *                      referencedColumnName:参照的主表的字段名称
     *
     *  在客户实体类上(一的一方)添加了外键配置所以对客户而言,也具备了维护外键的作用
     */
//    @OneToMany(targetEntity = LinkMan.class)
//    @JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id"
    /**
     * 放弃外键维护权
     *          mappedBy:对方配置关系的属性名称
     */
    @OneToMany(mappedBy = "customer",cascade = CascadeType.ALL)
    private Set<LinkMan> linkMans = new HashSet<>();

    public Long getCustId() {
        return custId;
    }

    public void setCustId(Long custId) {
        this.custId = custId;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustSource() {
        return custSource;
    }

    public void setCustSource(String custSource) {
        this.custSource = custSource;
    }

    public String getCustLevel() {
        return custLevel;
    }

    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }

    public String getCustIndustry() {
        return custIndustry;
    }

    public void setCustIndustry(String custIndustry) {
        this.custIndustry = custIndustry;
    }

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }

    public String getCustAddress() {
        return custAddress;
    }

    public void setCustAddress(String custAddress) {
        this.custAddress = custAddress;
    }

    public Set<LinkMan> getLinkMans() {
        return linkMans;
    }

    public void setLinkMans(Set<LinkMan> linkMans) {
        this.linkMans = linkMans;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName='" + custName + '\'' +
                ", custSource='" + custSource + '\'' +
                ", custLevel='" + custLevel + '\'' +
                ", custIndustry='" + custIndustry + '\'' +
                ", custPhone='" + custPhone + '\'' +
                ", custAddress='" + custAddress + '\'' +
                '}';
    }
}

LinkMan

@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;  //联系人备注

    /**
     * 配置联系人到客户的多对一关系
     *      使用注解的形式配置多对一关系
     *      1、配置表关系
     *          @ManyToOne:配置多对一关系
     *          referencedColumnName:对方的实体类字节码
     *      2、配置外键(中间表)
     *
     *  配置外键的过程,配置到了多的一方,就会在多的一方维护外键
     */
    @ManyToOne(targetEntity =  Customer.class)
    @JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")
    private Customer customer;

    public Long getLkmId() {
        return lkmId;
    }

    public void setLkmId(Long lkmId) {
        this.lkmId = lkmId;
    }

    public String getLkmName() {
        return lkmName;
    }

    public void setLkmName(String lkmName) {
        this.lkmName = lkmName;
    }

    public String getLkmGender() {
        return lkmGender;
    }

    public void setLkmGender(String lkmGender) {
        this.lkmGender = lkmGender;
    }

    public String getLkmPhone() {
        return lkmPhone;
    }

    public void setLkmPhone(String lkmPhone) {
        this.lkmPhone = lkmPhone;
    }

    public String getLkmMobile() {
        return lkmMobile;
    }

    public void setLkmMobile(String lkmMobile) {
        this.lkmMobile = lkmMobile;
    }

    public String getLkmEmail() {
        return lkmEmail;
    }

    public void setLkmEmail(String lkmEmail) {
        this.lkmEmail = lkmEmail;
    }

    public String getLkmPosition() {
        return lkmPosition;
    }

    public void setLkmPosition(String lkmPosition) {
        this.lkmPosition = lkmPosition;
    }

    public String getLkmMemo() {
        return lkmMemo;
    }

    public void setLkmMemo(String lkmMemo) {
        this.lkmMemo = lkmMemo;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

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

联系人的dao接口

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

客户的dao接口

 * 符合SpringDataJpa的dao层接口规范
 *          JpaRepository<操作的实体类类型,实体类中主键属性的类型>
 *              封装了基本的CRUD操作
 *          JpaSpecificationExecutor<操作的实体类类型>
 *              封装了复杂查询(分页)
 */
public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
}

applicationContext.xml

每次运行都会吧以前的表删掉,重新再创建

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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="com.rzk.pojo"/>
        <!--jpa的供应商适配器-->
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
        </property>
        <!--jpa的供应商适配器-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--配置是否自动创建数据库表-->
                <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="user" value="root"></property>
        <property name="password" value="123456"></property>
        <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/jap"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    </bean>

    <!--3、整合spring dataJpa-->
    <jpa:repositories base-package="com.rzk.dao" transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>

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

<!--    <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;5.aop&ndash;&gt;-->
<!--    <aop:config>-->
<!--        <aop:pointcut id="pointcut" expression="execution(* com.rzk.server.*.*(..))"/>-->
<!--        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>-->
<!--    </aop:config>-->

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

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class OneTomanyTest {
    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private LinkManDao linkManDao;

    /**
     * 保存一个客户,,保存一个联系人
     *  效果:客户和联系人作为独立的数据保存到数据库中
     *      联系人的外键为空
     *   为什么外键没有关联起来
     *   原因 ?
     *         实体类中没有配置关系
     */
    @Test
    @Transactional //配置事务
    @Rollback(false) //不自动回滚
    public void testAdd(){
        //创建一个客户,创建一个联系人
        Customer customer = new Customer();
        customer.setCustName("百度");

        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("李四");

        /**
         * 配置了客户到联系人的关系
         *      从客户的角度上,发送两条insert语句,发送一条更新语句更新数据库(更新外键)
         * 由于我们配置了客户到联系人的关系 : 客户可以对外键进行维护
         */
        linkMan.setCustomer(customer);
        customer.getLinkMans().add(linkMan);

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

关联关系

可以看到从表的外键和主表绑定在一起

级联添加和删除:

  • 操作一个对象的同时操作他的关联对象
    • 级联操作:
      • 1、需要区分操作主体
      • 2、需要在操作主体的实体类上,添加级联属性(需要添加到多表映射关系的注解上)
      • 3、cascade(配置级联)
        • CascadeType.ALL :配置所有
        • CascadeType.MERGE :更新
        • CascadeType.PERSIST :保存
        • CascadeType.REMOVE :删除
  • 级联添加
    • 案例:当我保存一个客户的同时保存联系人
      需要在操作主体的实体类上,配置cascade属性

测试级联添加

 /**
     * 级联添加:保存一个客户的同时,保存客户的所有联系人
     *
     *          需要在操作主体的实体类上,配置cascade属性
     */
    @Test
    @Transactional //配置事务
    @Rollback(false) //不自动回滚
    public void testCascadeAdd(){
        Customer customer = new Customer();
        customer.setCustName("one");

        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("two");

        linkMan.setCustomer(customer);
        customer.getLinkMans().add(linkMan);

        customerDao.save(customer);
    }

查看数据库:可看到已经同时插入成功

测试级联删除

需要在配置文件把创建语句改成修改

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

现在需要删除一号客户和它关联的对象也要删除

测试

    /**
     * 级联删除
     *      删除1号客户的同时,删除1号客户的所有联系人
     */
    @Test
    @Transactional //配置事务
    @Rollback(false) //不自动回滚
    public void testCascadeDel(){
        //1.查询1号客户
        Customer customer = customerDao.findOne(1l);
        //2.删除1号客户
        customerDao.delete(customer);
    }

可看到语句删除

查看数据库
就剩下一个2号

学习

posted @ 2020-08-14 18:21  Rzk  阅读(119)  评论(0编辑  收藏  举报