[Fixed] Validation failed for query for method upgrading from Spring Boot 3.1.5 to 3.2.0 – Java

by
Alexei Petrov
hibernate java spring-boot spring-data-jpa

Quick Fix: To resolve the validation error during upgrade from Spring Boot 3.1.5 to 3.2.0, ensure that the ID class used in the abstract superclass for entities extends Long, rather than being a generic type. This is necessary for Spring Data JPA 3.2.0 and above, especially when working with simple ID classes like Long.

The Problem:

After upgrading Spring Boot from version 3.1.5 to 3.2.0, several queries in the Repositories throw exceptions on application startup during the validation phase. The exception is caused by an inability to compare expressions of different types, resulting in errors like "Cannot compare left expression of type ‘java.lang.Object’ with right expression of type ‘java.lang.Long’." This issue affects queries that return List<ReferencedObject>, Optional<Entity>, and others, causing them to fail during validation.

The Solutions:

Solution 1: Ensure the ID Class Extends Long

In Spring Boot 3.2.0, abstract superclass for all entities must have an ID class that extends Long. This is because the generic type T for the ID class must extend Long in order to work.

In our case, we were using an abstract super class called AbstractEntity that used generics for the ID class with Entity as an interface with T getId(); method:

public abstract class AbstractEntity<T> implements Entity<T> {
    @Id
    private T id;
}

This worked until Spring Boot Data 3.1.5. From 3.2.0, the T class must not be a generic type. So we changed the code to:

public abstract class AbstractEntity<T extends Long> implements Entity<T> {
    @Id
    private T id;
}

The generic was introduced with composite Id-classes in mind. We will change the code and use Long directly since we never use composite ids in this project.

This solution fixed our problem and the queries started working again.

Q&A

What must the Generic type of the ID be?

The Generic type of the ID must extend Long

What’s the problem here?

The T class must not be a generic type from Spring Boot 3.2.0