我使用 Spring 和 Hibernate。在我的 DAO 中,我定义了一个会话工厂找不到的 NamedQuery,尽管我已将该 DAO 的包添加到 packagesToScan。
我的道:
/**
*
*/
package org.lalala.service.mytest;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.lalala.objects.Unit;
@NamedQueries
({
@NamedQuery
(
name="unit.findById",
query="from Unit u where u.unitid = :unitId"
)
})
public class MyTestDaoImpl implements MyTestDao
{
private SessionFactory sessionFactory;
public MyTestDaoImpl(SessionFactory sessionFactory)
{
super();
this.sessionFactory = sessionFactory;
}
/* (non-Javadoc)
* @see org.lalala.service.mytest.MyTestDao#getRandomUnit()
*/
@Override
public Unit getRandomUnit()
{
long unitid = 2891;
try {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query query = session.getNamedQuery("unit.findById");
query.setParameter("unitId", unitid);
Unit unit = (Unit) query.uniqueResult();
session.getTransaction().commit();
return unit;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
}
这里是用于提供会话工厂的 Spring config 方法:
@Bean
public AnnotationSessionFactoryBean getSessionFactory() {
final AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean ();
sessionFactory.setDataSource(getDataSource());
String[] packages = new String[]{"org.lalala.avalon.service.mytest"};
sessionFactory.setAnnotatedPackages(packages);
Properties properties = new Properties();
properties.put("hibernate.current_session_context_class", "thread");
sessionFactory.setHibernateProperties(properties);
return sessionFactory;
}
这里抛出的异常:
org.hibernate.MappingException: Named query not known: unit.findById
由于一些类似的 stackoverflow 问题,我将 hibernate @NamedQuery 注释替换为 JPA 等效项。没有帮助。