Kevin
Kevin

Reputation: 4128

Why am I restricted to placing NamedQuery annotation only on an entity class

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.

Upvotes: 4

Views: 2002

Answers (1)

Gonz
Gonz

Reputation: 1219

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);
}

Upvotes: 1

Related Questions