'JPA funciton findFieldById() extends JpaRepository didn't work properly?

@Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {
    String findNameById(Integer id);

    int getClassidById(Integer id);
}

I used those functions for a time and they worked well before, but today all of them return an entity object instead of single property
Such as findNameById(id) returns a Student object which cause
ClassCastException: db.entity.Student cannot be cast to java.lang.String
Even it can't return Map like :

Map<String, Object> findOneById(Integer id);

And My IDEA will notice 'Student' domain type or valid projection interface expected here

@Query("select s.name from Student s where s.id = ?1")
String findNameById(Integer id);

Only do I use @Query that they work properly. Does anyone has this problem?
(spring-data-jpa 2.2.5.RELEASE)



Solution 1:[1]

Your JPARepository references a Student object. Which is why it returns a Student with a specific Id that you request in that method argument.

However In your Native query, you are explicitly asking for s.name and for that reason you are getting back a String value of that name

You can get the object and extract the name from this object, if you would like to retain your JpaRepository<Student, Integer> extension to the StudentRepository. Get an Optional returned from your JPA. Then in your service layer extract the name

@Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {
    Optional<Student> findById(Integer id);
}

And in your service class,

public class StudentService {
    public void processStudent(){
          Optional<Student> student = studentRepository.findById(1);
          if(student.isPresent()){
            Student studentEntity = student.get();
            String name = studentEntity.getName();
          }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1