VictorGram
VictorGram

Reputation: 2661

Hibernate : how to create JPQL by concatenating strings?

I am trying to find out a way to concatenate strings to create a JPA native query. At present I have 3 queries just for having 1 or 2 different words. For example:

String queryAsc = select emp.id,role_id from employee left join roles 
                         on roles.id = emp.role_id      
                         where emp.id = :id
                         order by employee.created_date asc;

String queryDesc = select emp.id,role_id from employee left join roles 
                         on roles.id = emp.role_id
                         where emp.id = :id
                         order by employee.created_date desc;

Just because of the word difference of "asc" vs "desc", I have to write 2 different repository methods with JPA query as:

@Query(value = queryAsc,
       countQuery = countToMyEmployees, nativeQuery = true)
Page<Object[]>  findMyEmployeesAsc(@Param("id") String id, Pageable pageable);

 
@Query(value = queryDesc,
       countQuery = countToMyEmployees, nativeQuery = true)
Page<Object[]>  findMyEmployeesDesc(@Param("id") String id, Pageable pageable);

Is there a way to concatenate two strings in JPA query to avoid this kind of repetition?

Upvotes: 1

Views: 1118

Answers (1)

Akash R
Akash R

Reputation: 129

Try using Sort from the caller.

 if (condition) {
    obj.findMyEmployees("123",pageableObject , new Sort("employee.created_date "));
    } else {
    obj.findMyEmployees("234",pageableObject ,new Sort(Sort.Direction.DESC,"employee.created_date"));
    }

And rewrite the query as given below :

String query= select emp.id,role_id from employee left join roles 
                         on roles.id = emp.role_id
                         where emp.id = :id;
@Query(value = query,
       countQuery = countToMyEmployees, nativeQuery = true)
Page<Object[]>  findMyEmployees(@Param("id") String id, Pageable pageable, Sort sort);

Upvotes: 1

Related Questions