开发者

Hibernate @ManyToMany uses only FK from owning table to remove entries in connection table

I have @ManyToMany relationship of Author and Source entities, where Author is owning entity. When I remove author everything is OK and hibernate generates Hibernate: delete from author_source where author=?. But when I remove source, Hibernate generates same query for each occurrence of authorId in author_source table which had connection with deleted source. So this query also removes connection between other sources (if author had two sources, both connections are removed).

Author entity:

@Entity
@Table(name = "author")
public class Author implements Serializable {

    @Id
    @Column(name = "authorId")
    @GeneratedValue
    private Integer authorId;

    @SourceFormat // own formatter 
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTabl开发者_如何学JAVAe(
            name = "author_source",
            joinColumns = { @JoinColumn(name = "author") },
            inverseJoinColumns = { @JoinColumn(name = "source") }
    )
    private Set<Source> sources;
}

Source entity:

@Entity
@Table(name = "source")
public class Source implements Serializable {

    @Id
    @Column(name = "sourceId")
    @GeneratedValue
    private Integer sourceId;

    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "sources")
    private Set<Author> authors;
}

I want Hibernate to generate

delete from author_source where author=?

query when I remove author, and

delete from author_source where source=?

when I remove source. Is it possible or should I do it manually?


Maybe try to define the join table in both entities.

Make sure that the joinColumn and the inverseJoinColumn are opposites on the opposing sides of the relation.

  • joinColumn on one side == inverseJoinColumn on other side
  • inverseJoinColumn on one side == joinColumn on other side

.

@Entity
@Table(name = "author")
public class Author extends Serializable {

  ...

  @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  @JoinTable(name="author_source",
        joinColumns=@JoinColumn(name="author_id"),
        inverseJoinColumns=@JoinColumn(name="source_id")
  )
  private Set<Source> sources;

}

@Entity
@Table(name = "source")
public class Source extends Serializable {

  ...

  @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  @JoinTable(name="author_source",
        joinColumns=@JoinColumn(name="source_id"),
        inverseJoinColumns=@JoinColumn(name="author_id")
  )
  private Set<Author> authors;

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜