JPA:如何根据ID以外的字段值获取实体? [英] JPA: How to get entity based on field value other than ID?
问题描述
em.find()
)。 我知道我们可以使用查询并在稍后过滤结果。但是,有没有更直接的方法(因为这是一个非常常见的问题,据我所知)。 解决方案
问题就像你说的那样。
Hibernate有内置的 find()
,但是你必须构建您自己的查询以获取特定对象。我建议使用 Hibernate 的 Criteria
:
Criteria criteria = session.createCriteria(YourClass.class);
YourObject yourObject = criteria.add(Restrictions.eq(yourField,yourFieldValue))
.uniqueResult();
这会在您的当前字段上创建条件
类,添加列yourField等于值 yourFieldValue
的限制。 uniqueResult()
指示它带来唯一的结果。如果有更多的对象匹配,您应该检索一个列表。
List< YourObject> list = criteria.add(Restrictions.eq(yourField,yourFieldValue))。list();
如果您还有其他问题,请随时询问。希望这有助于。
In JPA (Hibernate), when we automatically generate the ID field, it is assumed that the user has no knowledge about this key. So, when obtaining the entity, user would query based on some field other than ID. How do we obtain the entity in that case (since em.find()
cannot be used).
I understand we can use a query and filter the results later. But, is there a more direct way (because this is a very common problem as I understand).
It is not a "problem" as you stated it.
Hibernate has the built-in find()
, but you have to build your own query in order to get a particular object. I recommend using Hibernate's Criteria
:
Criteria criteria = session.createCriteria(YourClass.class);
YourObject yourObject = criteria.add(Restrictions.eq("yourField", yourFieldValue))
.uniqueResult();
This will create a criteria
on your current class, adding the restriction that the column "yourField" is equal to the value yourFieldValue
. uniqueResult()
tells it to bring a unique result. If more objects match, you should retrive a list.
List<YourObject> list = criteria.add(Restrictions.eq("yourField", yourFieldValue)).list();
If you have any further questions, please feel free to ask. Hope this helps.
这篇关于JPA:如何根据ID以外的字段值获取实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!