您的位置:首页技术文章
文章详情页

java - JPA 中自定义对象和原生对象属性名不一致怎么解决?

【字号: 日期:2023-12-19 13:38:49浏览:66作者:猪猪

问题描述

有如下段代码 其中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;}

标签: java
相关文章: