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字段来做关联了。

原文地址:https://www.cnblogs.com/csonezp/p/7459919.html