【问题标题】:Hibernate Delete entity from manyTomany releationshipHibernate 从多对多关系中删除实体
【发布时间】:2018-05-12 16:59:07
【问题描述】:

在我的数据库中,一个帖子可以有很多类别,一个类别可能有很多帖子。我有一个帖子关系和另一个类别关系。这是他们的 JPA 映射:

发布实体:

@ManyToMany(cascade = {PERSIST, MERGE})
private Set<Category> categories = new HashSet<>();

类别实体:

@ManyToMany(mappedBy = "categories")
private Set<Post> posts = new HashSet<>();

其他操作正常,但是当我尝试删除帖子时:

@CacheEvict(cacheNames = "pinnedPosts", allEntries = true)
public void deletePost(long postId) {
    Optional<Post> optionalPost = postRepository.findById(postId);
    if (optionalPost.isPresent()) {
        Post post = optionalPost.get();
        for (Category category : post.getCategories()) {
            long newScore = post.getAuthor().getScore() - post.getLikesCount() * likeScore;
            post.getAuthor().setScore(newScore);
            category.getPosts().remove(post);
        }
        postRepository.deleteById(postId);
    } else {
        throw new PostNotFoundException();
    }
}

删除成功但hibernate抛出异常(我希望它被删除而没有任何异常!)。这是hibernate查询和hibernate抛出的异常(我不知道为什么查询会执行两次。这会导致问题吗?):

...
Hibernate: delete from post_categories where posts_id=?
Hibernate: delete from post_categories where posts_id=?
Hibernate: delete from post_likers where favorites_id=?
Hibernate: delete from post_likers where favorites_id=?
Hibernate: delete from post where id=?
Hibernate: delete from post where id=?

2018-05-12 20:59:53.621 ERROR 14652 --- [nio-8000-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.ObjectOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1] with root cause

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:67) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:54) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3325) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3562) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.action.internal.EntityDeleteAction.execute(EntityDeleteAction.java:99) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:599) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:473) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
...

【问题讨论】:

    标签: hibernate jpa spring-data persistence


    【解决方案1】:

    如果您在映射中使用连接表,我认为您不会遇到问题。在这种情况下,给定实体之一(例如,Post)将是关系的所有者(在其映射中将有 @JoinColumn 注释)。您将通过以下方式实现您想要的:

    entityManager.remove(post)
    for (Category category : post.getCategories()) {
         category.getPosts().remove(post);
    }
    

    可能对您有所帮助的链接
    How to properly implement Many-To-Many mapping

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 2012-10-10
      • 1970-01-01
      相关资源
      最近更新 更多