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 和你自定義的類屬性名稱不一樣的問題,你大可不必?fù)?dān)心,使用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. docker-compose中volumes的問題2. 我在centos容器里安裝docker,也就是在容器里安裝容器,報錯了?3. 在windows下安裝docker Toolbox 啟動Docker Quickstart Terminal 失敗!4. docker-machine添加一個已有的docker主機問題5. golang - 用IDE看docker源碼時的小問題6. docker不顯示端口映射呢?7. javascript - 連續(xù)點擊觸發(fā)mouseleave事件8. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””9. docker內(nèi)創(chuàng)建jenkins訪問另一個容器下的服務(wù)器問題10. mac里的docker如何命令行開啟呢?

網(wǎng)公網(wǎng)安備