4

私はHibernateと一緒にSpringを使用しています。私のDAOでは、セッションファクトリで検出されないNamedQueryを定義しましたが、そのDAOのパッケージをpackagesToScanに追加しました。

私のDAO:

/**
 * 
 */
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;
        }
    }    

}

そして、ここでセッションファクトリを提供するためのSpringconfigメソッド:

@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

同様のスタックオーバーフローの質問があるため、休止状態の@NamedQueryアノテーションを同等のJPAに置き換えました。助けにはならなかった。

4

2 に答える 2

6

名前付きクエリは、daoではなくエンティティに配置する必要があります

ここに例があります

于 2011-10-13T15:56:35.893 に答える
1

DAO に @MappedSuperclass のアノテーションを付けると、NamedQueries を DAO に入れることができます。DAO のパッケージまたは DAO クラス自体を、注釈付きパッケージ/クラスのリストに追加することを忘れないでください。

于 2011-11-24T07:22:12.910 に答える