如何正确处理JPA对象优化锁例外,同时处理多个事务请求?

因此,我正在开发一个简单的Spring MVC + JPA(休眠)项目,其中有用户可以发布帖子并在朋友帖子上发表评论(有点像一个小型社交网络)。我仍然相对较新的使用JPA Hibernate。因此,当我尝试从浏览器测试为某些任务(包含事务)发送多个请求时,在处理前一个请求时非常快速地发送2-3次,我得到一个 OptimisticLockException 。这是堆栈跟踪..

org.springframework.web.util.NestedServletException: Request processing   failed; nested exception is org.springframework.orm.ObjectOptimisticLockingFailureException: Object of class [org.facebookjpa.persistance.entity.Post] with identifier [19]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [org.facebookjpa.persistance.entity.Post#19]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)

现在,我该如何解决这个问题?当多个事务请求同时发生时,我如何正确处理此ObjectOptimisticLockException?有什么好的拍子是我应该遵循的吗?我需要使用某种悲观锁定机制吗?

这是我目前正在使用的DAO.提前致谢。:)

@Repository
@Transactional
public class PostDAOImpl implements PostDAO {

@Autowired
UserDAO userDAO;

@Autowired
CommentDAO commentDAO;

@Autowired
LikeDAO likeDAO;

@PersistenceContext
private EntityManager entityManager;

public PostDAOImpl() {

}

@Override
public boolean insertPost(Post post) {
    entityManager.persist(post);
    return true;
}

@Override
public boolean updatePost(Post post) {
    entityManager.merge(post);
    return true;
}

@Override
public Post getPost(int postId) {
    TypedQuery<Post> query = entityManager.createQuery("SELECT p FROM Post AS p WHERE p.id=:postId", Post.class);
    query.setParameter("postId", postId);
    return getSingleResultOrNull(query);
}

@Override
public List<Post> getAllPosts() {

    return entityManager.createQuery("SELECT p FROM Post AS p ORDER BY p.created DESC", Post.class).getResultList();
}

@Override
  public List<Post> getNewsFeedPostsWithComments(int userId) {
    List<Post> newsFeedPosts = getUserPosts(userId);
    newsFeedPosts.addAll(getFriendsPost(userDAO.getUser(userId)));

    for (Post post : newsFeedPosts) {
        post.setComments(commentDAO.getPostComments(post.getId()));
        post.setLikes(likeDAO.getPostLikes(post.getId()));
    }

    return newsFeedPosts;
}

public List<Post> getFriendsPost(User user) {
    List<Post> friendsPosts = new ArrayList<Post>();

    for (User u : user.getFriends()) {
        friendsPosts.addAll(getUserPosts(u.getId()));
    }

    return friendsPosts;
}


@Override
public List<Post> getUserPosts(int userId) {
    TypedQuery<Post> query = entityManager.createQuery("SELECT p FROM Post AS p WHERE p.user.id = :userId ORDER BY p.created DESC", Post.class);
    query.setParameter("userId", userId);
    return query.getResultList();
}

@Override
public List<Post> getUserPostsWithComments(int userId) {
    List<Post> userPostsWithComments = getUserPosts(userId);

    for (Post post : userPostsWithComments) {
        post.setComments(commentDAO.getPostComments(post.getId()));
        post.setLikes(likeDAO.getPostLikes(post.getId()));
    }

    return userPostsWithComments;
}

@Override
public boolean removePost(Post post) {
    entityManager.remove(post);
    return true;
}

@Override
public boolean removePost(int postId) {
    entityManager.remove(getPost(postId));
    return true;
}


private Post getSingleResultOrNull(TypedQuery<Post> query) {
    query.setMaxResults(1);
    List<Post> list = query.getResultList();
    if (list.isEmpty()) {
        return null;
    }
    return list.get(0);
}

}


答案 1

JPA 可以防止丢失更新,您不应忽略它。OptimisticLockException

您只需在通用异常处理程序中捕获它,并将用户重定向到当前正在执行的工作流的起点,指示必须重新启动流,因为它正在运行过时的数据。

但是,如果应用程序要求不需要防止丢失的更新异常,则只需从实体中删除批注,从而中断可序列化性。@Version

现在,您可能认为对新实体数据库快照的自动重试将解决此问题,但是由于加载时间版本仍低于数据库中的当前实体版本,因此您最终将遇到相同的乐观锁定异常。

此外,您可以使用悲观锁定(例如PESSIMISTIC_WRITEPESSIMISTIC_READ),这样,一旦获得行级锁定,其他事务就无法修改锁定的记录。


答案 2

推荐