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. angular.js - 百度支持_escaped_fragment_吗?2. 求救一下,用新版的phpstudy,数据库过段时间会消失是什么情况?3. node.js - win 下 npm install 遇到了如下错误 会导致 无法 run dev么?4. Python2中code.co_kwonlyargcount的等效写法5. python小白 关于类里面的方法获取变量失败的问题6. javascript - webpack1和webpack2有什么区别?7. java - 线上应用,如果数据库操作失败的话应该如何处理?8. django - Python error: [Errno 99] Cannot assign requested address9. python小白,关于函数问题10. [python2]local variable referenced before assignment问题
