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();
這樣執(zhí)行是可以的,但是如果我其中的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是不支持這種語法的。
關(guān)于你的問題:Entity 和你自定義的類屬性名稱不一樣的問題,你大可不必擔心,使用select new xx.xx.PersonResult(p.id,p.name.p.age) 語法時,jpa不會關(guān)心真實的字段叫什么名字,只要字段類型一致就可以了,因為這里采用是Java的構(gòu)造函數(shù)。調(diào)用構(gòu)造函數(shù)時只需要關(guān)心需要傳入幾個參數(shù)以及參數(shù)的類型
看下我代碼,這樣會直觀一點
@Query('select new com.zfxiao.pojo.AnnotherPerson(p.id,p.name,p.age) from Person p ')List<AnnotherPerson> findAnnotherPerson()
AnnotherPerson的構(gòu)造函數(shù)
public AnnotherPerson(Long personId, String name, Integer age) { this.personId = personId; this.name = name; this.age = age;}
相關(guān)文章:
1. javascript - JS設(shè)置Video視頻對象的currentTime時出現(xiàn)了問題,IE,Edge,火狐,都可以設(shè)置,反而chrom卻...2. java固定鍵值轉(zhuǎn)換,使用枚舉實現(xiàn)字典?3. 如何為每個應用程序配置tomcat 6的logs / catalina.out。(為sys.out,sys.err配置Web應用程序特定的日志文件)4. css - ionic中的柵格布局如何讓文字內(nèi)容多少不同的每一列中的內(nèi)容都能垂直居中?5. php自學從哪里開始?6. phpstady在win10上運行7. java - 我設(shè)置了cookie的max age,但是cookie依然在關(guān)閉游覽器后消失了8. vim - win10無法打開markdown編輯器9. 這是什么情況???10. javascript - 用jsonp抓取qq音樂總是說回調(diào)函數(shù)沒有定義
