Hibernate从manyTomany关系中删除实体

时间:2018-05-12 16:59:08

标签: hibernate jpa spring-data persistence

在我的数据库中,帖子可以是多个类别,一个类别可能有很多帖子。我有一个关系的帖子和另一个关于类别。这是他们的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]
...

1 个答案:

答案 0 :(得分:0)

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

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

链接,可以帮助您
How to properly implement Many-To-Many mapping

相关问题