jpa funciton findfieldbyid()扩展了jparepository不正常工作吗?
@Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {
String findNameById(Integer id);
int getClassidById(Integer id);
}
我使用了一段时间,它们以前运行良好,但是今天它们都返回实体对象而不是单个属性
例如FindNameById(ID)返回导致
classcastException的学生对象:db.entity.student不能将其施放到java.lang.string
即使它也无法返回地图:
Map<String, Object> findOneById(Integer id);
我的想法会注意到'student'''''''''''''''''''''''''''''
@Query("select s.name from Student s where s.id = ?1")
String findNameById(Integer id);
只有我使用@query
它们正常工作。有人有这个问题吗?
(弹簧data-jpa 2.2.5.Release)
@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 causeClassCastException: 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的jParepository引用了学生对象。这就是为什么它在该方法参数中返回带有特定ID的学生的原因。
但是,在本机查询中,您明确要求
s.name
,因此,您要回到该名称的字符串值,您可以获取对象并从此对象中提取名称,如果您想保留您的JParepository&Lt; Integer&gt;扩展到StudentRepository。从您的JPA中返回可选。然后在您的服务层中提取名称
和服务类,
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 nameYou 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
And in your service class,