Spring Jpa / Hibernate - 试图锁定时发现死锁;尝试重新启动事务

时间:2015-03-20 21:11:52

标签: java mysql spring hibernate jpa

我遇到了mysql和我正在开发的应用程序的死锁问题。该应用程序基于spring boot,integration和jpa,具有不同的线程,所有这些线程都可以访问此服务:

   @Override
    @Transactional()
    public List<TwitterUser> storeTwitterUsers(List<TwitterUser> twitterUsers)
    {
        logger.debug("Store list of users, total: " + twitterUsers.size());

        List<TwitterUser> savedUsers = new ArrayList<>();

        for ( TwitterUser twitterUser : twitterUsers ) {

            TwitterUser user  = getTwitterUserById(twitterUser.getTwitterId());

            if ( user != null ) {
                twitterUser.setId(user.getId());
                user = entityManager.merge(twitterUser);

            } else {
                //HERE THE EXCEPTION IS THROWN
                entityManager.persist(twitterUser);
                user = twitterUser;
            }

            entityManager.flush();

            savedUsers.add(user);
        }

        return savedUsers;
    }

    @Override
    @Transactional(readOnly = true)
    public TwitterUser getTwitterUserById(Long id)
    {
        Query query = entityManager.createQuery("from TwitterUser u where u.twitterId=:id");
        query.setParameter("id", id);

        TwitterUser twitterUser = null;

        //Throw Exception NoResultException
        try {
            twitterUser = (TwitterUser)query.getSingleResult();
        } catch (NoResultException e) {
            //no result found
        }

        return twitterUser;
    }

当方法 storeTwitterUsers 中有多个线程时,mysql会抛出此错误:

  

试图锁定时发现死锁;尝试重新启动交易

这是错误的完整堆栈跟踪:

http://pastebin.com/nZEvykux

我已经读过这两个问题了:

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

Getting "Deadlock found when trying to get lock; try restarting transaction"

但我的问题似乎略有不同,因为当几乎任何线程试图保留该对象时,我得到了异常。

在没有实施低级代码检查的情况下,是否有一种简洁明了的方法来解决问题? Spring Spring可以自动管理死锁情况吗?

非常感谢任何帮助,我正在努力解决这个错误!

0 个答案:

没有答案