+-

我收到错误:
Exception in thread "main" org.hibernate.HibernateException:
Could not obtain transaction-synchronized Session for current thread
主要
ppService.deleteProductPart(cPartId, productId);
@Service( “productPartService”)
@Override
public void deleteProductPart(int cPartId, int productId) {
productPartDao.deleteProductPart(cPartId, productId);
}
@Repository( “productPartDAO”)
@Override
public void deleteProductPart(ProductPart productPart) {
sessionFactory.getCurrentSession().delete(productPart);
}
@Override
public void deleteProductPart(int cPartId, int productId) {
ProductPart productPart = (ProductPart) sessionFactory.getCurrentSession()
.createCriteria("ProductPart")
.add(Restrictions.eq("part", cPartId))
.add(Restrictions.eq("product", productId)).uniqueResult();
deleteProductPart(productPart);
}
怎么解决?
更新:
如果我修改这样的方法:
@Override
@Transactional
public void deleteProductPart(int cPartId, int productId) {
System.out.println(sessionFactory.getCurrentSession());
}
它返回:
SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] collectionQueuedOps=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])
但是如果我删除@Transactional它会以异常结束:
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
我通过添加@Transactional来实现它,但现在我得到了org.hibernate.MappingException:未知实体:ProductPart虽然我将.uniqueResult()链接到Criteria.怎么解决?
最佳答案
错误org.hibernate.MappingException:未知实体:ProductPart表示没有名称为ProductPart的实体.解决此问题的一种方法是将Class对象传递给createCriteria方法:
createCriteria(ProductPart.class)
从API开始,使用String和Class的区别如下:
Session.createCriteria(String)
Create a new Criteria instance, for the given entity name.
Session.createCriteria(Class)
Create a new Criteria instance, for the given entity class, or a
superclass of an entity class, with the given alias.
如果传递String,则hibernate会查找名称为ProductPart的实体.
点击查看更多相关文章
转载注明原文:java – HibernateException:无法获取当前线程的事务同步会话 - 乐贴网