【发布时间】:2020-10-02 20:15:07
【问题描述】:
entityManager.remove() VS JPQL DELETE 查询
我知道关系的一侧是所有者,而标记为映射者的另一侧是非所有者。
关系以所有者的持久性保存在数据库中,并在删除时删除。 我知道移除非所有者方不会消除关系。 see this link
到目前为止一切顺利。
根据我的经验,使用 JPQL 查询删除非所有者也会删除关系。我不清楚为什么!有没有说服力的解释?
下面的代码 sn-ps 显示了我的概念测试用例:
非所有者
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
@ManyToMany(mappedBy = "books")
private Set<Author> authors;
}
所有者:
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany
private Set<Book> books;
}
测试 1
public void persistingRelationOwnerPersistsRelationSuccessfully(){
Book book = new Book("nonOwner");
entityManager.persist(book);
Author author = new Author("owner", new HashSet<>(Arrays.asList(book)));
entityManager.persist(author);
entityManager.flush();
}
日志:
Hibernate: insert into book (title, id) values (?, ?)
Hibernate: insert into author (name, id) values (?, ?)
Hibernate: insert into author_books (authors_id, books_id) values (?, ?)
测试 2
public void removingRelationOwnerRemovesRelationSuccessfully(){
//persist book and author
entityManager.remove(author);
entityManager.flush();
}
日志:
Hibernate: insert into book (title, id) values (?, ?)
Hibernate: insert into author (name, id) values (?, ?)
Hibernate: insert into author_books (authors_id, books_id) values (?, ?)
Hibernate: delete from author_books where authors_id=?
Hibernate: delete from author where id=?
测试 3
public void removingNonOwnerWillThrowException(){
//persist book and author
entityManager.remove(book);
entityManager.flush();
}
日志:(如预期)
Hibernate: insert into book (title, id) values (?, ?)
Hibernate: insert into author (name, id) values (?, ?)
Hibernate: insert into author_books (authors_id, books_id) values (?, ?)
Hibernate: delete from book where id=?
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
测试 4
public void removingNonOwnerWithQueryWillRemoveRelation(){
//persist book and author
Query query = entityManager.createQuery("delete from Book b where b.title = 'nonOwner'");
System.out.println("affectedRows = " + query.executeUpdate());
}
日志:(意外行为)
Hibernate: insert into book (title, id) values (?, ?)
Hibernate: insert into author (name, id) values (?, ?)
Hibernate: insert into author_books (authors_id, books_id) values (?, ?)
Hibernate: delete from author_books where (books_id) in (select id from book where title='nonOwner')
Hibernate: delete from book where title='nonOwner'
affectedRows = 1
【问题讨论】: