简体   繁体   中英

Spring Boot generates invalid MySQL query (only_full_group_by)

I'm using Spring Boot 1.5.2 and the following @Query:

@Query(value = "SELECT m FROM Message m WHERE m.from.userId = :myId OR m.to.userId = :myId GROUP BY m.from.userId, m.to.userId ORDER BY m.date DESC")
List<Message> chatOverview(@Param("myId") final Long myUserId);

The intention of the query is to create a chat messenger overview, where you see the last message of each conversation you had. It works fine for me in dev, but in production (newer MySQL database version) I get this error:

java.sql.SQLSyntaxErrorException: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'message0_.message_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

I read in this thread what the reason for this change was, however I couldn't find a way to fix this with JPA / Spring. I cannot change any settings in the production MySQL database and I would like to avoid any upgrading in Spring either. How can I fix my query?

Here is the definition and purpose of the GROUP BY (see section 4.7) clause:

The GROUP BY construct enables the aggregation of result values according to a set of properties.

That means it is used only if you're aggregating (sum, avg, max, min, ...) the value(s) of a field(s). But in your case I don't see any aggregation function. So just remove the GROUP BY clause and everything should be fine:

SELECT m FROM Message m WHERE m.from.userId = :myId OR m.to.userId = :myId ORDER BY m.date DESC

Grouping on userId doesn't make sense too because all the entities returned by this query will have the same value for this field.

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