查询我的 JPA 提供程序 (Hibernate) 以获取的集合一个实体的
我有一个看起来像这样的实体:
身份证号(PK) 姓名
其他业务属性和关联...
我需要我的 DAL(以 hibernate 作为提供程序的 JPA)返回与某些约束相关的实体列表(或者只是返回所有实体),但我不是返回实体本身我只想接收 Id 和 Name 属性。
我知道这可以通过 HQL/SQL 来实现(例如:从实体中选择 id、名称...),但我不想走这条路。
我正在考虑以某种方式将这对定义为实体的组成部分,并认为这可能对我有帮助,但我不确定这是否“合法”,因为 Id 就是 PK。
此场景的逻辑是有一个文本框,它异步查询 Web 服务(并通过它的 DAL)查找相关实体,一旦选择一个实体,就会将其作为一个整体加载并发送到前端。
更新:
我现在非常有信心我将使用 JPA 的 CriteriaBuilder 接口来构建查询,因此 JPQL/HQL 完全不可能。
我想我可能正在寻找相当于 Hibernate 的 resultTransformer 的 JPA(并且我将给它一个非持久类)。
希望得到任何反馈,
一泰
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 Hibernate's resultTransformer (and I'll give it a non persisted class).
Would appreciate any feedback,
Ittai
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
抱歉,忽略这一点,因为我错过了问题中的“不想执行 HQL”部分
HQL select 子句非常灵活。如果您只需要两个属性,您可以使用
其中 MyClass 是带有构造函数(id,name)的 java 类。
如果您不想创建单独的类,HQL 可以返回 Object 类型的数组。
请在此处阅读有关 select 子句的详细信息文档
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
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.
Please read the detail about select clause here from documentation
鉴于您的要求,我想 HQL 或 JPQL 是最好的选择,您多久更改一次字段名称?
您可以使用 @NamedQuery 将 HQL 保存在同一实体类中,这样如果更改字段名称,您就不会错过该更改。
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.