【问题标题】:Spring Data JPA Querydsl doesn't work with projectionSpring Data JPA Querydsl 不适用于投影
【发布时间】:2016-09-08 18:46:39
【问题描述】:

我已经实现了 Spring Data JPA 并使用 Querydsl 作为搜索条件。春季文档中给出的更改很少,效果很好。

下面给出了我的 REST 控制器方法

@RequestMapping(value = "/testdsl", method = RequestMethod.GET)
 Iterable<User> index(
@QuerydslPredicate(root = User.class) Predicate predicate)
{
  return userRepository.findAll(predicate);
} 

下面给出了存储库,注释方法很好地为我提供了投影对象。

public interface UserRepository extends CrudRepository<User, Integer>,
QueryDslPredicateExecutor<User>, QuerydslBinderCustomizer<QUser>
{
  //Collection<OnlyName> findAllProjectedBy();
  //OnlyName findProjectedById(Integer id);

@Override
default public void customize(QuerydslBindings bindings, QUser root)
{

    bindings.bind(String.class)
    .first((StringPath path, String value) ->    path.containsIgnoreCase(value));
 }
 }

然后我实现了这个投影,我得到了作为响应返回的整个实体类的一个子集。

public interface IUserProjection  {
 //...all required getters..
 }

现在我希望我的 Querydsl 返回这些投影对象。 我们有这种组合的样本吗?我正在使用 spring boot 1.4.0.RELEASE

【问题讨论】:

    标签: spring-data spring-data-jpa projection querydsl


    【解决方案1】:

    你可以这样做,但你需要一个具体的类...

    class UserProjection {
    
      @QueryProjection
      public UserProjection(long id, String name){
         ...
      }
    
    }
    

    然后您的查询将如下所示(在 QueryDSL 3 中):

    query.from(QTenant.tenant).list(new QUserProjection(QTenant.tenant.id, QTenant.tenant.name));
    

    编辑:

    queryDSL 4 的查询如下所示:

    List<UserProjection> dtos = query.select(new QUserProjection(QTenant.tenant.id, QTenant.tenant.name))
                                  .from(tenant).fetch();
    

    【讨论】:

    • 我用过spring query dsl(问题已编辑)..这些似乎没什么不同,什么是QTenant
    • 您从未将它与自动生成的 Q 类一起使用?它们是类型安全的自动生成的类,您可以使用它们来避免使用字符串文字
    • 我使用那些自动生成的实体,QUserProjection 呢?我需要生成它吗,你有这个 qprojection 类的示例吗?
    • 如果您已经在生成 QEntity,它们应该以相同的方式生成
    • 我正在使用 com.querydsl.jpa.JPQLQuery ,它没有这个限制方法......
    猜你喜欢
    • 2021-03-22
    • 2018-12-16
    • 1970-01-01
    • 2020-06-16
    • 2015-02-14
    • 2017-09-27
    • 2012-11-09
    • 1970-01-01
    • 2018-11-05
    相关资源
    最近更新 更多