HibernateException:无法获取当前线程的事务同步会话

时间:2014-09-19 12:04:50

标签: java spring hibernate

我收到错误:

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。如何解决?

3 个答案:

答案 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. 

Session.createCriteria(Class)

  

为给定的实体类创建新的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定义。

Ref

相关问题