Bilgehan
Bilgehan

Reputation: 1227

Spring JPA @Query Annatotion disadvantages

Hi I use spring jpa to access my data in my spring boot project.I am wondering that is there any difference between @Query annatotation and critearia api in jpa.Are they totaly same or is there any difference(Their writing styles are different ,and I mean any performance or other issue between them) Mostly I prefer @Query annotation it looks simple.Or any other option some one can advice like @Query or criteria api in spring jpa.And is there any disadvantages of @Query style?

@Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();

List<Book> findBooksByAuthorNameAndTitle(String authorName, String title) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Book> cq = cb.createQuery(Book.class);

Upvotes: 2

Views: 1036

Answers (1)

abhinav kumar
abhinav kumar

Reputation: 1803

Using @Query we can pass static query or pre compiled query so we can perform both select and non-select operations on the data where as Criteria is suitable for executing Dynamic Queries such requirements occurs when data are know at run time but using criteria api we can only perform select operations on the data.

For example

@Query(value = "SELECT u FROM User u")
List<User> findAllUsers(Sort sort);

We can also work with pre compiled query using @Query For Example

@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByStatusAndNameNamedParams(
  @Param("status") Integer status, 
  @Param("name") String name);)

Dynamic queries like

Criteria cr = session.createCriteria(Employee.class);

// To get records having salary more than 2000
cr.add(Restrictions.gt("salary", 2000));

// To get records having salary less than 2000
cr.add(Restrictions.lt("salary", 2000));

Actual use of Dynamic queries comes when we'll encounter the need for building SQL statements based on conditions or data sets whose values are only known at runtime. And, in those cases, we can't just use a static query So we can't just use the @Query annotation since we can't provide a static SQL statement.In such case we use Criteria API

For more info follow the link provided @Query and Criteria

Upvotes: 1

Related Questions