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();
會報(bào)錯(cuò),是不是jpql new對象的時(shí)候不支持別名嗎?
問題解答
回答1:你的代碼
@Query(select new com.xx.yy.PersonResult(p.id as personId,p.name,p.age) from Person p) List<PersonResult> findPersonResult();
你把a(bǔ)s去掉就可以了,jpa是不支持這種語法的。
關(guān)于你的問題:Entity 和你自定義的類屬性名稱不一樣的問題,你大可不必?fù)?dān)心,使用select new xx.xx.PersonResult(p.id,p.name.p.age) 語法時(shí),jpa不會關(guān)心真實(shí)的字段叫什么名字,只要字段類型一致就可以了,因?yàn)檫@里采用是Java的構(gòu)造函數(shù)。調(diào)用構(gòu)造函數(shù)時(shí)只需要關(guān)心需要傳入幾個(gè)參數(shù)以及參數(shù)的類型
看下我代碼,這樣會直觀一點(diǎn)
@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. php - mysql 模糊搜索問題2. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時(shí)間會消失是什么情況?3. html - 爬蟲時(shí)出現(xiàn)“DNS lookup failed”,打開網(wǎng)頁卻沒問題,這是什么情況?4. javascript - 求幫助 , ATOM不顯示界面!!!!5. php - 微信開發(fā)驗(yàn)證服務(wù)器有效性6. [python2]local variable referenced before assignment問題7. python中怎么對列表以區(qū)間進(jìn)行統(tǒng)計(jì)?8. javascript - js setTimeout在雙重for循環(huán)中如何使用?9. java - idea創(chuàng)建多modules項(xiàng)目后,tomcat啟動失敗10. javascript - 我的站點(diǎn)貌似被別人克隆了, google 搜索特定文章,除了域名不一樣,其他的都一樣,如何解決?
