1

I have a data access class that exposes basic operations for an entity class used on a web site:

public class UserDataAccessService {

   public User login(User u)...
   public User findByUsername(String username)...

I want to define all HQL/SQL queries in this data access class, but I'm having trouble using the hibernate @NamedQuery annotation; Hibernate keeps saying that it can't find the named query. I don't intend to define lookup/find methods in the entity classes because I don't feel it's the appropriate location for it.

I am using annotations and hibernate.cfg.xml only, so where can I declare these queries so that Hibernate can find them?

user646584
  • 3,621
  • 5
  • 25
  • 27

2 Answers2

1

If you annotate your DAO with @MappedSuperclass then you can put your NamedQueries in the DAO. Don't forget to add the package of the DAO or the DAO-class itself to the list of annotated packages/classes in your Hibernate Configuration

Hans
  • 43
  • 3
0

You can write queries in respective XML mapping files.

//---
<query name="findUser"><![CDATA[select o from User o]]>
</query>
//---

Edit :

Named native query:

<sql-query name="findUser">
<return alias="user" class="com.User"/>
//-- native query
</sql-query>

From Documentation :

Named SQL queries can be defined in the mapping document and called in exactly the same way as a named HQL query.

These queries need to be placed in respective mapping(hbm.xml) files.

Nayan Wadekar
  • 11,444
  • 4
  • 50
  • 73
  • There is no "query" element in hibernate.cfg.xml, so that's not an option. – user646584 Mar 13 '11 at 21:48
  • @user646584 : query element need to be placed in mapping file(hbm.xml) not in configuration file(cfg.xml) which you are trying to do. Anyways edited my answer might help you. – Nayan Wadekar Mar 19 '11 at 11:57