我收到错误:
Exception in thread "main" org.hibernate.HibernateException:
Could not obtain transaction-synchronized Session for current thread
主要
ppService.deleteProductPart(cPartId, productId);
@服务(" productPartService&#34)
@Override
public void deleteProductPart(int cPartId, int productId) {
productPartDao.deleteProductPart(cPartId, productId);
}
@Repository(" productPartDAO&#34)
@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
。如何解决?
答案 0 :(得分:7)
错误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.
为给定的实体类创建新的Criteria实例,或者a 具有给定别名的实体类的超类。
如果传递一个String,那么hibernate会查找名称为ProductPart
的实体。
答案 1 :(得分:6)
使用Hibernate 4.x和Spring 4.x,只需在@Repository 之后添加@Transactional它将解决此同步异常。
答案 2 :(得分:1)
您必须启用事务支持(<tx:annotation-driven>
或@EnableTransactionManagement
)并声明transactionManager,它应该通过SessionFactory工作。
您必须将@Transactional
添加到@Repository
@Transactional
中的@Repository
Spring可以将事务支持应用到您的存储库中。
您的Student类没有@javax.persistence.*
注释@Entity
,我假设该类的映射配置已通过XML定义。