Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write cross-table queries with QueryDSL and Spring's Repository

I've build a DAL which uses Spring's Repositories to manage CRUD operations on a MySQL DB through Hibernate and JPA. In particular this is my Repository definition

package my.dal.repository;

import my.domain.dal.User;

import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface IUserRepository extends CrudRepository<User, String>, QueryDslPredicateExecutor<User>{

}

With this definition I'm able to execute CRUD operations using QueryDSL Predicates through the extension of the QueryDslPredicateExecutor interface and the findAll(Predicate) method.

The problem I'm facing is that this way I'm not able to make cross-table queries. Indeed, I cannot use QueryDSL's join facilities because I don't have a HibernateQuery.

What is the right way to implement the join operation with Spring Repositories and QueryDSL?

Thank you

like image 967
gvdm Avatar asked Apr 17 '14 17:04

gvdm


1 Answers

Solved.

Below I write the steps needed to execute a QueryDSL query with Spring Repositories

  1. Acquire the EntityManager used in the application context by adding the EntityManager attribute in the Service class with the @PersistenceContext annotation

    @PersistenceContext
    EntityManager em;
    

    This way the em attribute will link to the EntityManager bean defined in the Spring application context.

  2. Instantiate a JPAQuery object and use it

    QUser qUser = QUser.user;
    JPQLQuery query = new JPAQuery(em);
    User charlie = query
        .from(qUser)
        .where(qUser.username.eq("charlie"))
        .uniqueResult(qUser);
    

Now we can use the JPQLQuery object to execute joins over different tables.

Hope this helps

like image 83
gvdm Avatar answered Sep 21 '22 00:09

gvdm