Why I limited myself to placing the NamedQuery annotation only for the entity class

The logical location for request annotations is a data access class that uses save, retrieve, etc. data for the object.

However, Hibernate throws an exception β€œNo query defined for this name” if I put the NamedQuery annotation in a class that is not marked with @Entity.

Why is Hibernate or JPA restricting named queries to objects only? Could this be a future feature?

There are several unreasonable workarounds, such as using an empty object to store requests , which makes me think that it would be useful not to limit this. I know that I can use the XML configuration, but named queries for non-entities will still be useful.

+4
source share
1 answer

If you check the JpaRepository , you will see that you can declare them in another way:

Annotated Named Query Configuration

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

}

Declare a query with a 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);
}
+1
source

Source: https://habr.com/ru/post/1599201/


All Articles