来自查询的响应无法映射到Pojo类Spring Boot

时间:2019-05-09 08:19:32

标签: mysql sql spring spring-boot spring-data-jpa

每个查询的响应都应映射到poja类。

我写了一个本地查询

@Query(value="SELECT new QuestionJsonTotalAnswer(q.question) FROM mydb.question q", nativeQuery=true)
List<QuestionJsonTotalAnswer> showAnswersOfQuestions();

转换器类

public class QuestionJsonTotalAnswer {
    String question;
    // constructors, getters and setters
}

但是错误是:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本以使用正确的语法   第1行的'(q.question)FROM mydb.question q'附近

在application.properties中

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

注意:当我通过List<Object>获得响应时,在没有pojo类的情况下它可以正常工作。但是我需要通过pojo类来避免嵌套数组。

2 个答案:

答案 0 :(得分:3)

您需要使用这样的投影。

@Query(value="SELECT q.question FROM mydb.question q", nativeQuery=true)
List<QuestionJsonTotalAnswer> showAnswersOfQuestions();

public interface QuestionJsonTotalAnswer {
    String getQuestion();
} 

答案 1 :(得分:1)

正如J4mes所说,您应该投影到本机查询。

@Query(value="SELECT q.question FROM mydb.question q", nativeQuery=true)
List<QuestionJsonTotalAnswer> showAnswersOfQuestions();

public interface QuestionJsonTotalAnswer {
    String getQuestion();
} 

使用hql查询时,您可以照常在问题中给出的方式使用pojo类。 附加信息 - 如果查询的标题

  1. 返回question使用String getQuestion()
  2. 返回不正确的标题,例如count(q.question),给出类似     count(q.question) as countQuestion在查询中,然后使用Long getCountQuestion()
  3. 进行投影