Is it possible to query with list of objects using JPA like foreach tag?

Viewed 427

Let's say I have a query like this:

Query object

public class myObject {
    private String code;
    private String name;
}

query method

@Query(nativeQuery = true,value = "...")
findByAcodeAndBname(List<MyObject> queryObject);

Pseudocode of the query

 select a.code, b.name from tableA a 
  left join table b on a.column = b.column 
 where a.code = ${} b.name = ${}

Since it could cause performance issues just simply using foreach code in Java to do the query, how do I map every pair of a.code and b.name using native JPA query like mybatis foreach tag? Or is it posssible?

1 Answers

I think you don't need native query here, because the costs of querying data from the database and transfering it over network are higher than any related Java operations.

Instead of native query you can use JPQL query, e.g.

@Query("select new com.tsypanov.domain.HasIdAndNameDto(e.id, e.name)" +
    " from ManyFieldsEntity e " +
    "where e.name = :name")
List<HasIdAndName> findAllByNameUsingDto(@Param("name") String name);

Here we call constructor of DTO from JPQL query passing the fields from our entity. The DTO class must have the specified constructor:

@RequiredArgsConstructor
public class HasIdAndNameDto {

  private final Long id;
  private final String name;

}
Related