分类 Hibernate 下的文章

在JPA的@OneToOne(一对一)及@OneToMany(一对多)有一个orphanRemoval属性。

例如一個作者(Author)有多本书籍著作(Book),则在Author类别中会有Book的集合:

Author.java

public class Author {
    ...
    @OneToMany(mappedBy="author", orphanRemoval=true)
    private Set<Book> bookSet;
    
    // getters and setters ommitted  
}

Book.java

public class Book {
    ...
    @ManyToOne
    private Author author;
    
    // getters and setters ommitted
}

orphanRemoval预设值为false。若设为true,则当Author物件中的一本bookbookSet移除時,资料库Book资料表的该本书的列会被删除。

orphan代表孤儿,orphanRemoval=true的意思就是child沒有parent时会被删除。

而和CascadeType.REMOVE不同的是,CascadeType.REMOVE是当Authur物件从资料表中删除時,其所关联的child,也就是所属的bookSet中的每一个Book也会从资料表被一并删除。

https://matthung0807.blogspot.com/2018/06/jpa-onetoone-onetomanyorphanremoval.html

@Entity
public class Shirt implements Serializable {

    @Id
    @Size(max=9)
    private String id;

    @ElementCollection
    @CollectionTable(
        name = "SHIRT_COLORS",
        joinColumns=@JoinColumn(name = "id", referencedColumnName = "id")
    )
    @Column(name="color")
    private List<String> colors = new ArrayList<String>();
    ...
https://stackoverflow.com/questions/22075199/jpa-elementcollection-list-specify-join-column-name

@Column(nullable=false) 是生成模式的指令。从该类生成的数据库列将在实际数据库中标记为不可空。

optional=false 是一条运行时指令。它的主要功能与懒加载有关。除非你记得设置 optional=false,否则你就无法懒加载一个非集合映射实体(因为 Hibernate 不知道那里应该有一个代理还是一个空值,除非你告诉它空值是不可能的,所以它可以生成一个代理)。

https://stackoverflow.com/questions/3331907/what-is-the-difference-between-manytooneoptional-false-vs-columnnullable-f

This is known issue in Hibernate, see https://hibernate.atlassian.net/browse/HHH-8805

Solution is to add @org.hibernate.annotations.ForeignKey(name = "none") on the mapped side.

class Parent {

  @OneToMany(mappedBy="parent", cascade=CascadeType.ALL, orphanRemoval=true)
  @OrderColumn(name="childIndex")
  @org.hibernate.annotations.ForeignKey(name = "none")
  public List<Child> getChildren() {
    return children;
  }

}

Note: Prefer the JPA 2.1 introduced javax.persistence.ForeignKey instead. The native annotation is deprecated.

answerd by Bustanil Arifin and sophros How do I disable Hibernate foreign key constraint on a bidirectional association?