在Hibernate会话工厂找不到的DAO注释中定义的NamedQuery

时间:2011-10-13 15:53:04

标签: hibernate spring jpa hibernate-annotations named-query

我将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配置方法:

@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问题,我用等效的JPA替换了hibernate @NamedQuery注释。没有帮助。

2 个答案:

答案 0 :(得分:4)

您必须将命名查询放在您的实体上,而不是放在dao

here is an example

答案 1 :(得分:1)

如果使用@MappedSuperclass注释DAO,则可以将NamedQueries放入DAO中。不要忘记将DAO或DAO类本身的包添加到带注释的包/类列表中。