java - JPA 中自定义对象和原生对象属性名不一致怎么解决?
问题描述
有如下段代码 其中person是jpa的entity对象,personResult是自定义对象
@Query(select new com.xx.yy.PersonResult(p.id,p.name,p.age) from Person p) List<PersonResult> findPersonResult();
这样执行是可以的,但是如果我其中的personResult对象中的id是叫personId,上面的代码该如何改?
我用过
@Query(select new com.xx.yy.PersonResult(p.id as personId,p.name,p.age) from Person p) List<PersonResult> findPersonResult();
会报错,是不是jpql new对象的时候不支持别名吗?
问题解答
回答1:你的代码
@Query(select new com.xx.yy.PersonResult(p.id as personId,p.name,p.age) from Person p) List<PersonResult> findPersonResult();
你把as去掉就可以了,jpa是不支持这种语法的。
关于你的问题:Entity 和你自定义的类属性名称不一样的问题,你大可不必担心,使用select new xx.xx.PersonResult(p.id,p.name.p.age) 语法时,jpa不会关心真实的字段叫什么名字,只要字段类型一致就可以了,因为这里采用是Java的构造函数。调用构造函数时只需要关心需要传入几个参数以及参数的类型
看下我代码,这样会直观一点
@Query('select new com.zfxiao.pojo.AnnotherPerson(p.id,p.name,p.age) from Person p ')List<AnnotherPerson> findAnnotherPerson()
AnnotherPerson的构造函数
public AnnotherPerson(Long personId, String name, Integer age) { this.personId = personId; this.name = name; this.age = age;}
相关文章:
1. JAVASCRIPT 构造函数和原型互相指向问题?求助!!!2. css - 移动端 oppo 手机之 Border-radius3. html5 - 移动端UC浏览器兼容问题4. android - 具体的空指针是在哪????5. javascript - 前端富文本编辑器 wangeditor 如何展示富文本?6. docker pull 错误?7. 关于《Effective Java中文版(第2版)》的问题8. mysql 创建root 用户出错,这是什么原因?mysql 中也没有root用户9. python - 请问matplotlib.pyplot.save的路径如何更改10. angular.js - ionic 弹窗样式