简体   繁体   中英

Unable to convert a @Query result to a POJO

I have a custom query on a table in Spring Boot. I would like to store the results in a POJO.

public interface LegalRepository extends JpaRepository<LegalEntity, Long> {
@Query(value = "...SELECT company_id as id ,AVG((...)) as average ...." ,nativeQuery = true)
        List<QueryObject> returnMeanValue();
}

LegalEntity is the main entity for data table and QueryObject is the derived one.

The result of query is as follows:

company_id | average

1 | 1560850.633333333

2 | 2365230.933333333

3 | 13714243.266666666

4 | 15375235.133333333

This is my POJO:

@Entity
public class QueryObject {

@Id
Integer company_id;

@Column(name="average")
Double average;
public Integer getCompany_id() {
    return company_id;
}
public void setCompany_id(Integer company_id) {
    this.company_id = company_id;
}
public Double getAverage() {
    return average;
}
public void setAverage(Double average) {
    this.average = average;
}
@Override
public String toString() {
    return "QueryObject [company_id=" + company_id + ", average=" + average + "]";
}
public QueryObject(Integer company_id, Double average) {
    super();
    this.company_id = company_id;
    this.average = average;
}

}

Note that company_id is unique.

After executing:

@Bean
public void getUp() {

 List<QueryObject> qo;
 qo = leg_rep.returnMeanValue();
 log.info(qo.get(0).toString());

}

The following exception is thrown:

org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.Object[]] to type [QueryObject] for value '{1, 1560850.633333333}';

nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.Integer] to type [QueryObject]

How should I solve this problem?

  1. Create an interface QueryObject

  2. Create getters:

public interface QueryObject {

    Integer getCompany_id();
    Double getAverage();

}

Spring Data JPA will then automatically create/fill your result object.

Check the spring docs for details: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM