在我的网络应用程序中,我使用Stateless sessions
与Hibernate
在inserts
和updates
上获得更好的效果。
它与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个简单的实体(ProductType
,RawMaterialType
和PriceHistory
)。
computeDelta
和computePrice
只是没有数据库内容的算法函数。
retrieveAllWithHistory
函数是使用Play framework model
函数从数据库中获取一些数据的函数。
因此,此代码检索一些数据,编辑一些数据,创建新数据,最后保存所有数据。
为什么我的MySQL
锁定例外,H2
没有例外?
答案 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。