Skip to content
Advertisement

Response from query couldn’t map to pojo class spring boot

Every response from query should be mapped to a poja class.

I have written a native query

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

Converter class

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

But the error is:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘(q.question) FROM mydb.question q’ at line 1

In application.properties

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

Note : Its working fine without pojo class when I get the response through List<Object>. But I need to get through pojo class to avoid nested arrays.

Advertisement

Answer

As J4mes says, you should you projection to native queries.

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

public interface QuestionJsonTotalAnswer {
    String getQuestion();
} 

You can use pojo class when you use hql queries as usual you given in the question. Additional information – If the title of the query

  1. returns question the use String getQuestion(),
  2. returns not a proper title, eg count(q.question), give a alises like count(q.question) as countQuestion in query then project it with Long getCountQuestion()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement