java - JPA 中自定义对象和原生对象属性名不一致怎么解决?
PHPz
PHPz 2017-04-18 10:56:49
0
1
583

有如下段代码 其中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对象的时候不支持别名吗?

PHPz
PHPz

学习是最好的投资!

reply all(1)
阿神

Your code

@Query(select new com.xx.yy.PersonResult(p.id as personId,p.name,p.age) from Person p)
 List<PersonResult> findPersonResult();

You put as去掉就可以了,jpa which does not support this syntax.



About your question: If the name of Entity is different from your custom class attribute, you don’t have to worry, just use select new xx.xx.PersonResult(p.id,p.name.p.age) 语法时,jpa不会关心真实的字段叫什么名字,只要字段类型一致就可以了,因为这里采用是Java的构造函数。调用构造函数时只需要关心需要传入几个参数以及参数的类型

Look at my code, it will be more intuitive

@Query("select new com.zfxiao.pojo.AnnotherPerson(p.id,p.name,p.age) from Person p ")
List<AnnotherPerson> findAnnotherPerson()

Constructor of AnnotherPerson

public AnnotherPerson(Long personId, String name, Integer age) {
    this.personId = personId;
    this.name = name;
    this.age = age;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template