I have 2 entities Instructor and Section with many-to-many association between them. The intermediate table is ‘teaches’. I have a query that fetches all instructors of a given department along with their number of sections they taught in a given year. The result is a record defined as
public record InstructorWithNumberOfSections(Integer instructorId, Long numberOfSections) {}
and is fetched by this repository-method:
@Transactional(readOnly = true)
@Query(value = """
SELECT i.id AS instructor_id, COUNT(i.id) AS number_of_sections FROM instructor i LEFT JOIN teaches t ON i.id = t.instructor_id WHERE i.dept_id = ?1 AND t.year = ?2 GROUP BY i.id
""", nativeQuery = true)
List<InstructorWithNumberOfSections> findNumberOfSectionsForInstructors(String departmentName, Integer year);
When I hit the REST endpoint that calls that query, i get this exception:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.example.university.model.dto.InstructorWithNumberOfSections]
I searched the web and found some blogs using interfaces for DTOs so I changed InstructorWithNumberOfSections to an interface as follows:
public interface InstructorWithNumberOfSections {
Integer getInstructorId();
Long getNumberOfSections();
}
``` and it works!
I don't know the problem with classes/records for native SQL queries. It is worth noting that they work well with JPQL queries (SELECT new com.example.university.model.dto.InstructorWithNumberOfSections(i.id, COUNT(i.id) FROM ....). Any help will be appreciated.
Mohammad Ballour is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.