Spring JPA selecting specific columns



@Entity
data class User(
  var id: Long,
  var name: String?,
  var age: Int,
  ...
)

class UserSummary(var id:Long, var name:String?)

interface UserRepository : JpaRepository<User, Long> {
  fun findOneById(id: Long): User?
  fun <VIEW> findOneById(id: Long, type: Class<VIEW>): VIEW?
  fun <VIEW> findByIdIn(ids: List<Long>, type: Class<VIEW>): List<VIEW>

  // Using @Query failed to narrow the select column by passing type
  // @Query("from org.example.User where id in :ids")
  // fun <VIEW>findByIds(@Param("ids") ids: List<Long>, type:Class<VIEW>): List<VIEW>
}

...

fun procSomething() {
  val user = userRepository.findOneById(ar, UserSummary::class.java)
  val users = userRepository.findByIdIn(ar, UserSummary::class.java)
}

See also