Select only specific column in Spring with Querydsl?

14,441

Solution 1

If You want to use QueryDSL predicate and have single attribute response you could use just QueryDSL directly without using spring-data.

// where entityManager is a JPA EntityManager
JPAQuery<?> query = new JPAQueryFactory(entityManager);

BooleanExpression paramEmployee = qEmployee.company.id.eq(new Long(data.get("company").toString()));

List<Long> id = query.select(qEmployee.id).from(qEmployee).where(paramEmployee).fetch();

Solution 2

I'm afraid querydsl integration with spring only allows for construction of dynamic predicates and not full queries as indicated per spring data documentation.

I suppose though you could just use the getId() method from your Employee class without modifying the code.

Share:
14,441
Acep Muhamad Saepuloh
Author by

Acep Muhamad Saepuloh

Updated on June 09, 2022

Comments

  • Acep Muhamad Saepuloh
    Acep Muhamad Saepuloh almost 2 years

    Let say i have model called Employee with 70 column. How can i implement query SELECT id from t_employee in spring + querydsl without modifying lot of code from this code.

    BooleanExpression paramEmployee = qEmployee.company.id.eq(new Long(data.get("company").toString()));
    Iterable<Employee> employeeReportIterable =employeeRepository.findAll(paramEmployee);
    
  • Acep Muhamad Saepuloh
    Acep Muhamad Saepuloh almost 7 years
    yup but that mean i need to iterate over the list with full model field right ! and split only the id to arraylist(double process) is there any way to return only the id not entire the model field T-T
  • megalucio
    megalucio almost 7 years
    Not that I know of, at least using querydsl, which to be honest I'm not sure it is the best choice given the complexity of your query. Perhaps you could look into creating a custom query with @Query annotation.
  • Fernando
    Fernando almost 7 years
    I would also like to know how to do that, because even if I use Query annotation like @megalucio said, I would lose the ability to filter with predicate.
  • WeGa
    WeGa over 5 years
    not found select() method in query (Got QueryDsl-JPA 3.2.0)