Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

hibernate - JPA 2.0: Load a subset of fields for an entity

I have an Entity named address. The address Entity has several fields, one of which is CITY. I've created a query by calling entityManager.createQuery but my query only includes the CITY field in the select clause (because I only want to load that field). The CITY field is of type String. When I get my resultList, I do not get a list of Address objects but instead a list of Object[].

Is there any way to have a list of Address created instead of a list of Object[]? My JPA provider is hibernate, latest version. I want a solution that does not require the use of anything Hibernate specific.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is possible with constructor expressions in your query. Normally you would use this with a custom DTO, but it should work with the entity too. First create an additional constructor in your entity taking only the needed fields:

public Address() {
    //default constructor
}

public Address(String city) {
    this.city = city;
}

Your query could then look like this:

select new your.package.Address(a.city) from Address a where ...

Note that the resulting object is not attached to the EntityManager, so changes to it won't be automatically persisted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...