我遇到错误:
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: Unknown entity: ProductPart 尽管我链接了 .uniqueResult( ) 到 Criteria。如何解决?
最佳答案
错误 org.hibernate.MappingException: Unknown entity: ProductPart 表示没有名称为 ProductPart 的实体。解决此问题的一种方法是将 Class 对象传递给 createCriteria 方法,如下所示:
createCriteria(ProductPart.class)
从API来看,使用String和Class的区别如下:
Session.createCriteria(String)
Create a new Criteria instance, for the given entity name.
Create a new Criteria instance, for the given entity class, or a superclass of an entity class, with the given alias.
如果您传递一个字符串,则 hibernate 会查找名称声明为 ProductPart 的实体。
关于java - hibernate 异常 : Could not obtain transaction-synchronized Session for current thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25933532/