有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用JPQL删除关系的非所有者也会删除关系

实体管理器。remove()VS JPQL DELETE查询

我知道关系的一方是所有者,另一方标记为mapped by,是非所有者

关系以所有者的持久性保存在数据库中,并随着其删除而删除。 我知道移除非所有者方不会消除关系。 see this link

到目前为止还不错

根据我的经验,用JPQL查询删除非所有者,也会删除关系。我不清楚为什么!?有什么有说服力的解释吗

下面的代码片段展示了我的概念测试用例:

非所有者

@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

共 (1) 个答案

  1. # 1 楼答案

    这可能是一个错误,因为这应该取决于Book#authors关联的级联设置,对于delete-DML语句,该设置可能会被忽略。你应该把一个问题记录在一个复制器上https://hibernate.atlassian.net/