4

A logical place to place named query annotations is on a data access class, one that deals the logic of saving, retrieving etc. data for an entity.

However, Hibernate throws an exception "No query defined for that name" if I place a NamedQuery annotation on a class which is not marked with @Entity.

Why does Hibernate or JPA limit named queries to be only placed on entities? Could it be a future feature?

There are a few crude workarounds such as using an empty entity to hold queries, which makes me think that it would useful to not be restricted like this. I know I can use an XML config, but named queries on non-entities would still be useful.

Community
  • 1
  • 1
Kevin
  • 4,070
  • 4
  • 45
  • 67

1 Answers1

1

If you check the JpaRepository you can see that you can declare them in other way:

Annotation based named query configuration

@Entity
@NamedQuery(name = "User.findByEmailAddress",
  query = "select u from User u where u.emailAddress = ?1")
public class User {

}

Declare query at the query method using @Query

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.emailAddress = ?1")
  User findByEmailAddress(String emailAddress);
}
Gonz
  • 1,198
  • 12
  • 26
  • Is this a Spring specific feature? I don't think it is part of JPA or Hibernate. – Kevin Jul 23 '15 at 04:36
  • Thanks for the link. Do you know any solution if one is not using Spring? – Kevin Jul 23 '15 at 04:49
  • Take a look at this: http://stackoverflow.com/questions/602397/how-do-i-externalize-named-queries-in-a-hibernate-annotations-app You can add the queries to the `package-info.java` file. – Gonz Jul 23 '15 at 04:51