【发布时间】:2017-02-08 08:12:22
【问题描述】:
我编写类以使用休眠查询获取数据。当我使用
从 EntityManager 获取会话时Session session=null;
sessionFactory=entityManager.unwrap(SessionFactory.class);
session=(Session) sessionFactory.getCurrentSession();
或
Session session = (Session) entityManager.getDelegate();
并且会话开始要求将会话转换为 EntityManager
public class BranchCustomRepositoryImpl implements BranchCustomRepository{
@PersistenceContext
private EntityManager entityManager;
private SessionFactory sessionFactory;
public Branch findByOrgOrgIdAndBranchId(String orgId, String branchId) {
//Session session=null;
//sessionFactory=entityManager.unwrap(SessionFactory.class);
//session=(Session) sessionFactory.getCurrentSession();
Session session = (Session) entityManager.getDelegate();
System.out.println("BranchCustomRepositoryImpl");
Long orgId2=Long.valueOf(orgId);
Long branchId2=Long.valueOf(branchId);
try{
Query query= (Query)((EntityManager) session).createQuery("from Branch b where b.org.orgId=:orgId AND b.branchId=:branchId");
query.setParameter("orgId", orgId2);
query.setParameter("branchId", branchId2);
return (Branch) query.uniqueResult();
}catch(Exception e){
System.out.println("Exception"+e.toString());
}finally{
try {
if(session!=null){
session.close();
System.out.println("session closed");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
出现类似错误,
java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [java.lang.Long (n/a)]
如果有人知道如何在 spring data jpa 中使用休眠查询,请帮助我
【问题讨论】:
-
您有一个使用 JPQL 可以完美表达的查询,因此无需使用“Hibernate API”
标签: java hibernate session spring-data-jpa