使用QueryDSL和Spring的Repository编写交叉表查询

6

我建立了一个使用Spring Repositories来通过Hibernate和JPA管理MySQL数据库的CRUD操作的DAL。特别地,这是我的Repository定义:

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>{

}

通过扩展QueryDslPredicateExecutor接口和findAll(Predicate)方法,我可以使用QueryDSL谓词执行CRUD操作。但是,我面临的问题是无法进行跨表查询。实际上,我不能使用QueryDSL的连接功能,因为我没有一个HibernateQuery。如何在Spring Repositories和QueryDSL中实现连接操作是正确的方法?谢谢。
1个回答

3

已解决。

以下是使用Spring Repositories执行QueryDSL查询所需的步骤:

  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);
    
现在,我们可以使用JPQLQuery对象来执行不同表之间的连接查询。
希望这可以帮到你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接