surya
surya

Reputation: 2749

Spring Data JPA Querydsl doesn't work with projection

I have implemented Spring Data JPA and used Querydsl for search conditions. Which works fine with few changes as given in spring docs.

My REST controller method is given below

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

and the repository is given below, commented methods give me projected objects nicely.

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));
 }
 }

And then I have this projection implemented where I get a subset of the whole entity class which is returned as the response.

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

Now I want my Querydsl to return these projected objects. Do we have any sample of such combination? I am using spring boot 1.4.0.RELEASE

Upvotes: 1

Views: 2702

Answers (1)

Ulises
Ulises

Reputation: 9635

You can do that but you'll need a concrete class...

class UserProjection {

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

}

And then your query would look like (in QueryDSL 3):

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

EDIT:

Query for queryDSL 4 would look like this:

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

Upvotes: 0

Related Questions