[英]JPA Many To Many remove entity
我使用Hibernate(通過JPA )。 有一種刪除實體的方法:
public void delete(final ID id) { entityManager.createQuery(String.format("delete from %s e where e.id = :id", entityClass.getSimpleName()))
.setParameter("id", id).executeUpdate();
}
我刪除實體(與many2many關系):
休眠日志:
Hibernate: delete from author_to_book where (author_id) in (select id from author where id=?)
Hibernate: delete from author where id=?
誰負責從綁定表中刪除關聯? 畢竟,我的代碼僅指定從主表中刪除。 這個怎么運作?
對應:
@Entity
public class Author extends BaseEntity implements IAuthor {
@Column
private String name;
@JoinTable(name = "author_to_book",
joinColumns = {@JoinColumn(name = "author_id")} ,
inverseJoinColumns = {@JoinColumn(name = "book_id")}
)
@ManyToMany(targetEntity = Book.class, fetch = FetchType.LAZY)
@OrderBy("title ASC")
private Set<IBook> books = new HashSet<>();
圖書實體沒有到作者實體的映射
對於JPA而言,使用字符串構造查詢SQL並不是一個好主意。 應該使用JPQL或Criteria API。 通常,關聯的擁有方負責從聯接表中刪除行。 對於雙向關系,聯接表中的行也可以從另一側刪除。 這實際上取決於JPA的實現。 據我所知, CMobileCom JPA可以從雙方管理聯接表。
免責聲明:我是CMobileCom JPA的開發人員,該輕量級的JPA實現同時適用於Android和Java JDBC。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.