Heim  >  Fragen und Antworten  >  Hauptteil

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对象的时候不支持别名吗?

PHPzPHPz2742 Tage vor545

Antworte allen(1)Ich werde antworten

  • 阿神

    阿神2017-04-18 10:58:49

    你的代码

    @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;
    }

    Antwort
    0
  • StornierenAntwort