KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > persister > entity > NamedQueryLoader


1 //$Id: NamedQueryLoader.java,v 1.3 2005/04/23 19:08:18 oneovthafew Exp $
2
package org.hibernate.persister.entity;
3
4 import java.io.Serializable JavaDoc;
5
6 import org.apache.commons.logging.Log;
7 import org.apache.commons.logging.LogFactory;
8 import org.hibernate.AssertionFailure;
9 import org.hibernate.FlushMode;
10 import org.hibernate.HibernateException;
11 import org.hibernate.Query;
12 import org.hibernate.engine.EntityKey;
13 import org.hibernate.engine.SessionImplementor;
14 import org.hibernate.loader.entity.UniqueEntityLoader;
15
16 /**
17  * Not really a <tt>Loader</tt>, just a wrapper around a
18  * named query.
19  * @author Gavin King
20  */

21 public final class NamedQueryLoader implements UniqueEntityLoader {
22     private final String JavaDoc queryName;
23     private final EntityPersister persister;
24     
25     private static final Log log = LogFactory.getLog(NamedQueryLoader.class);
26
27     public NamedQueryLoader(String JavaDoc queryName, EntityPersister persister) {
28         super();
29         this.queryName = queryName;
30         this.persister = persister;
31     }
32
33     public Object JavaDoc load(Serializable JavaDoc id, Object JavaDoc optionalObject, SessionImplementor session)
34     throws HibernateException {
35         
36         if (optionalObject!=null) {
37             throw new AssertionFailure("cannot supply object to query loader");
38         }
39         
40         if ( log.isDebugEnabled() ) {
41             log.debug("loading entity: " + persister.getEntityName() + " using named query: " + queryName );
42         }
43         
44         Query query = session.getNamedQuery(queryName);
45         if ( query.getNamedParameters().length>0 ) {
46             query.setParameter(
47                     query.getNamedParameters()[0],
48                     id,
49                     persister.getIdentifierType()
50             );
51         }
52         else {
53             query.setParameter( 0, id, persister.getIdentifierType() );
54         }
55         query.setFlushMode(FlushMode.NEVER).list();
56         
57         // now look up the object we are really interested in!
58
// (this lets us correctly handle proxies and multi-row
59
// or multi-column queries)
60
return session.getPersistenceContext()
61                 .getEntity( new EntityKey( id, persister, session.getEntityMode() ) );
62
63     }
64 }
Popular Tags