我收到错误消息:

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);
}

@存储库(“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.

Session.createCriteria(Class)



如果您传递一个String,那么 hibernate 将查找其名称声明为ProductPart的实体。

10-07 19:44