Spring Boot Add Query Parameter Into the Select Statement

Viewed 77

I have a query like so (which i put one of the parameters of the method into the DTO projection):

@Query("SELECT new com....dto.SomeDTO(x.id, x.name, :abc) FROM SomeEntity x WHERE x.property = property")
List<SomeDTO> getSomething(@Param("property") String property, 
                           @Param("abc") String abc);

And when i try to run the program i get the error:

Unable to locate appropriate constructor on class [com....dto.SomeDTO]. Expected arguments are: int, java.lang.String

It seems like jpql is ignoring the parameter passed into the DTO.


However if i wrap the param value with jpql concat it works. Like so:

@Query("SELECT new com....dto.SomeDTO(x.id, x.name, CONCAT(:abc, '')) FROM SomeEntity x WHERE x.property = property")
List<SomeDTO> getSomething(@Param("property") String property, 
                           @Param("abc") String abc);

Here is the SomeDTO:

@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SomeDTO {
  private Integer id;
  private String name;

  public SomeDTO(Integer id, String name, String parameter) {
    if ("something".equals(parameter)) { //doSomething }
    this.id = id;
    this.name = name;
  }
}

what is happening here, why does the second one works but not the first. Should i keep doing like the second one or is there a better solution for this?

0 Answers
Related