Unable to Resolve Class in Hibernate Query Instantiation - Could not resolve class named for instantiation error

124 Views Asked by At

I'm working on a Spring Boot project where I'm using Hibernate to execute custom queries. In one of my repository interfaces (UsersRepository), I have a method annotated with @Query to retrieve aggregate data using a DTO class (UserBatchCountDto). However, when I try to instantiate the DTO within the query, Hibernate throws a SemanticException stating it couldn't resolve the class.

Error I'm receiving :

Caused by: org.hibernate.query.SemanticException: Could not resolve class 'UserBatchCountDto' named for instantiation

UsersRepository class :

import static org.test.model.UserBatchCountDto.*;

@Repository
public interface UsersRepository extends JpaRepository<UserEntity, UserEntity.UserEntityId> {

      @Query("""
             SELECT new UserBatchCountDto(c.batchId, COUNT(c))
             FROM UserEntity u
             WHERE u.dateUserReceived BETWEEN :startDate AND :endDate
             GROUP BY u.batchId""")
      List<UserBatchCountDto> findUserCountPerBatchForDateRange(@Param("startDate") ZonedDateTime startDate, @Param("endDate") ZonedDateTime endDate);
}

UserBatchCountDto class :

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserBatchCountDto {
   private String batchId;
   private Long batchRecordCount;
}

UserEntity class :

@Builder
@Data
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "user_submissions")
@AllArgsConstructor
@NoArgsConstructor
@IdClass(UserEntity.UserEntityId.class)
public class UserEntity {

    @Column(name = "batch_id")
    @NotNull
    private String batchId;

    @Column(name = "date_user_received")
    @NotNull
    private ZonedDateTime dateUserReceived;

}

What I've Tried:

  • Verified the package structure of the DTO class UserBatchCountDto to ensure it matches the import statement.
  • Double-checked the import statement for UserBatchCountDto for any typos or errors.
  • Ensured that the DTO class UserBatchCountDto is compiled and included in the project's build path.
  • Restarted the application server to check for any caching or loading issues.
  • When I gave the query with full path SELECT new org.test.model.UserBatchCountDto(c.batchId, COUNT(c)) its working, which I intend to refactor and make cleaner.
1

There are 1 best solutions below

0
NoDataFound On

Hibernate does not know the context, the class in which the query is.

Use the FQCN:

 @Query("""
             SELECT new org.test.model.UserBatchCountDto(c.batchId, COUNT(c))
             FROM UserEntity u
             WHERE u.dateUserReceived BETWEEN :startDate AND :endDate
             GROUP BY u.batchId""")

Doing that should work and also help your IDE in case of refactoring.