使用Hibernate和MySQL超出锁定等待超时(使用play框架)

时间:2013-10-29 16:57:39

标签: java mysql hibernate jpa playframework

在我的网络应用程序中,我使用Stateless sessionsHibernateinsertsupdates上获得更好的效果。

它与H2 database(在开发模式下播放框架中使用的那个)工作正常。

但是当我用MySQL测试时,我得到以下异常:

ERROR ~ Lock wait timeout exceeded; try restarting transaction
ERROR ~ HHH000315: Exception executing batch [Lock wait timeout exceeded; try restarting transaction]

以下是代码:

public static void update() {
    Session session = (Session) JPA.em().getDelegate();
    StatelessSession stateless = this.session.getSessionFactory().openStatelessSession();

        try {

            stateless.beginTransaction();

            // Fetch all products
            {
                List<ProductType> list = ProductType.retrieveAllWithHistory();
                for (ProductType pt : list) {
                    updatePrice(pt, stateless);
                }
            }

            // Fetch all raw materials
            {
                List<RawMaterialType> list = RawMaterialType.retrieveAllWithHistory();
                for (RawMaterialType rm : list) {
                    updatePrice(rm, stateless);
                }
            }
        } catch (Exception ex) {
            play.Logger.error(ex.getMessage());
            ExceptionLog.log(ex, Thread.currentThread());
        } finally {
            stateless.getTransaction().commit();
            stateless.close();
        }
}

private static void updatePrice(ProductType pt, StatelessSession stateless) {
    pt.priceDelta = computeDelta();
    pt.unitPrice = computePrice();

    stateless.update(pt);

    PriceHistory ph = new PriceHistory(pt, price);

    stateless.insert(ph);
}

private static void updatePrice(RawMaterialType rm, StatelessSession stateless) {
    rm.priceDelta = computeDelta();
    rm.unitPrice = computePrice();

    stateless.update(rm);

    PriceHistory ph = new GoodPriceHistory(rm, price);

    stateless.insert(ph);
}

在此示例中,我有3个简单的实体ProductTypeRawMaterialTypePriceHistory)。 computeDeltacomputePrice只是没有数据库内容的算法函数。 retrieveAllWithHistory函数是使用Play framework model函数从数据库中获取一些数据的函数。

因此,此代码检索一些数据,编辑一些数据,创建新数据,最后保存所有数据。

为什么我的MySQL锁定例外,H2没有例外?

1 个答案:

答案 0 :(得分:0)

我不确定你为什么要在finally块中提交。试试这个结构:

try {
    factory.getCurrentSession().beginTransaction();
    factory.getCurrentSession().getTransaction().commit();
} catch (RuntimeException e) {
    factory.getCurrentSession().getTransaction().rollback();
    throw e; // or display error message
}

此外,您可以查看documentation