开发者

Querying my JPA provider (Hibernate) for a collection of <Id,Name> of an entity

开发者 https://www.devze.com 2023-02-12 18:50 出处:网络
I have an entity which looks something like this: Id(PK) Name Other business properties and associations...

I have an entity which looks something like this:

Id (PK) Name

Other business properties and associations...

I have the need for my DAL (JPA with hibernate as provider) to return a list of the entities which correlate to some constraints (or just return them all) but instead of returning the entities themselves I'd like to receive only the Id and the Name properties.

I know this can be achieved with HQL/SQL (something like: select id,name from entity where...) but I don't want to go down that road.

I was thinking of somehow defining the pair a compositioned part of the entity and thought that might help me but I'm not sure that's "legal" as the Id is the PK.

The logic for this scenario is to have a textbox which asynchronously queries the web-service (and through it the DAL) for the relevant entities and once an entity is selected then it is loaded as a whole and shipped to the front-end.

Update:

I am now pretty confident I'll be using the CriteriaBuilder interface of JPA to build queries and so JPQL/HQL is completely off the table.

I think I might be looking for JPA's equivalent to Hiber开发者_高级运维nate's resultTransformer (and I'll give it a non persisted class).

Would appreciate any feedback,

Ittai


Sorry ignore this as I missed "dont want to do HQL" part in your question

The HQL select clause is very flexible. If you need just two properties you can use

select new MyClass(foo.id,foo.name) From Foo foo

where MyClass is your java class with constructor (id,name).

If you don't want to create separate class, HQL can return array of type Object.

select foo.id,foo.name From Foo foo

Please read the detail about select clause here from documentation


Given your requirement I guess HQL or JPQL is the best option and how often you will change the field names?
You can use @NamedQuery to hold the HQL in the same entity class so you won't miss that change if you change the Field names.

0

精彩评论

暂无评论...
验证码 换一张
取 消