mardi 19 octobre 2021

How do Spring repositories instantiate results from query methods?

Assume the following (jdbc) repository:

interface Repo : CrudRepository<MyType, Long> {
    @Query("select * from blabla")
    fun abc(): List<MyType>
}

Both for the method abc() and the methods included from the parent interface the auto generated runtime implementation of the Repo interface knows how to serialise result sets into instances of MyType subject to certain restrictions.

How does Spring have access to the type information from the generic parameter at runtime? How does it manage to create lists of the correct runtime types based solely on the type information provided in the interface?

My understanding is that I would not have sufficient information from a signature like mapV1() below to instantiate my result, and therefore I would need to introduce a second parameter with type Class<T> as shown in mapV2():

class Mapper {
   fun <T> mapV1(source: Any): T {
       /* 
       try to instantiate a result 
       of type T reflectively
       */
   }
   fun <T> mapV2(source: Any, klass: Class<T>): T {
       /* 
       try to instantiate a result 
       of type T reflectively
       */
   }
}

Somehow Spring avoids this problem.





Aucun commentaire:

Enregistrer un commentaire