JPA:如何根据ID以外的字段值获取实体? [英] JPA: How to get entity based on field value other than ID?

查看:638
本文介绍了JPA:如何根据ID以外的字段值获取实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JPA(Hibernate)中,当我们自动生成ID字段时,假定用户不知道这个键。所以,在获取实体时,用户会根据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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆