Home > Enterprise >  JPQL Query - No constructor taking error?
JPQL Query - No constructor taking error?

Time:07-16

I have a Card entity class with many columns. I used dto because I want to get some columns from this Entity. I created a DTO class and wrote a query to CardRepositoryCustom. But when I try to run the Query I get various errors "No constructor taking".

My dto class:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class CardDTO {
    private String test1;
    private String test2;
    private String test3;
    private String test4;
}

JPQL RepositoryCustom :

@Repository
@Transactional
public class CardRepositoryCustom {

    public CardDTO test1() {
        JpaResultMapper jpaResultMapper = new JpaResultMapper();
        String q =  "SELECT          " 
                    "   c.test1  " 
                    "FROM            " 
                    "   CardEntity c ";
        Query query = entityManager.createQuery(q);
        try {
            return jpaResultMapper.uniqueResult(query, CardDTO.class);
        } catch (NoResultException nre) {
            return null;
        }
    }
}

Errors:

java.lang.RuntimeException: No constructor taking: java.lang.String
at org.qlrm.mapper.JpaResultMapper.findConstructor(JpaResultMapper.java:107) ~[qlrm-1.7.1.jar:na]
    at org.qlrm.mapper.JpaResultMapper.uniqueResult(JpaResultMapper.java:64) ~[qlrm-1.7.1.jar:na]
    at ....

I know how to fix this error. You just need to write the following constructor in the DTO class as shown below.

public CardDTO(String test1) {
    this.setTest1(test1);       
}

Here I am curious, if I want test2, test3, test4 and write Query in Custom class, should there be as many constructors in DTO class as that number?

I think this method is really inefficient. Is there any solution I am not aware of?

CodePudding user response:

This seems to be more about QLRM than JPA or Spring.

Judging from the error message the constructor has to match the arguments provided. Probably the easiest variant is to always provide all arguments, possibly with a value of null or some other literal. The query in your example would then become.

SELECT c.test1, null, null, null FROM CardEntity c 

Of course QLRM just provides a JpaResultMapper and it would probably not too difficult to provide your own, or offer a PR to QLRM that inspects names of the result set and tries to match them to parameter names or the constructor.

  • Related