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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

There is no "query" element in hibernate.cfg.xml, so that's not an option.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.