zoukankan      html  css  js  c++  java
  • Spring Data Jpa(Hibernate) OneToMany

    这个其实非常简单。假设有topic 和 subscriber两个实体类,不考虑关联关系,则连个类的代码如下:

    /**
     * Created by csonezp on 2017/8/31.
     */
    @Entity
    @Table
    public class Topic implements Serializable{
    
        private static final long serialVersionUID = -7752115605498533357L;
    
        @Id
        @GeneratedValue
        private Integer id;
    
        private String name;
    
    
    }
    /**
     * Created by csonezp on 2017/8/31.
     */
    @Table
    @Entity
    public class Subscriber implements Serializable {
        private static final long serialVersionUID = 5105575565495750284L;
        @Id
        @GeneratedValue
        private Integer id;
    
        private String email;
    }

    非常简单的两个类。

    现在要做一个onetomany关联,先来个最简单的,这时候topic代码如下:

    @Entity
    @Table
    public class Topic implements Serializable{
    
        private static final long serialVersionUID = -7752115605498533357L;
    
        @Id
        @GeneratedValue
        private Integer id;
    
        private String name;
    
        @OneToMany(cascade = {CascadeType.ALL},fetch=FetchType.EAGER,orphanRemoval=true)
        List<Subscriber> subscribers;
        
    }

    在topic类中添加红色的部分即可。cascade = {CascadeType.ALL} 是用来设置级联操作的,设置ALL就是所有Topic的操作都会同时更新Subscriber;fetch=FetchType.EAGER就是关闭lazy查询,拿到topic对象的时候就已经把subscriber都查出来了;orphanRemoval=true意思是在topic里移除subscriber时将subscriber记录也删除,而不是只指删除关联关系。

    这里是建立关联表的形式做的onetomany映射,还可以用添加关联字段的方式。

    @Entity
    @Table
    public class Topic implements Serializable{
    
        private static final long serialVersionUID = -7752115605498533357L;
    
        @Id
        @GeneratedValue
        private Integer id;
    
        private String name;
    
        @OneToMany(cascade = {CascadeType.ALL},fetch=FetchType.EAGER,orphanRemoval=true)
        @JoinColumn(name = "topic_id")
        List<Subscriber> subscribers;
    
    }

    加红色的这一行代码,就不会生成中间表,而是在subscriber表中加入一个topic_id字段来做关联了。

  • 相关阅读:
    vscode的一些常用、神奇操作
    vue2.x中使用v-model进行父传子
    js设置,获取,删除cookies
    Linux虚拟机克隆后网卡UUID问题
    jQuery ajax 请求HttpServlet返回[HTTP/1.1 405 Method not allowed]
    byte、二进制、十进制数值之间的转换
    sqlite-jdbc jar包下载过程笔记
    windows系统bat方式启动tomcat出现java.lang.OutOfmemoryError:PermGen Space 错误
    DIV内容垂直居中
    在HTML中实现和使用遮罩层
  • 原文地址:https://www.cnblogs.com/csonezp/p/7459919.html
Copyright © 2011-2022 走看看