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

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

问题描述

在JPA(Hibernate)中,当我们自动生成ID字段时,假设用户不知道这个key.因此,在获取实体时,用户将根据 ID 以外的某些字段进行查询.在这种情况下我们如何获取实体(因为不能使用 em.find()).

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 具有内置的 find(),但是您必须构建自己的查询才能获取特定对象.我推荐使用 HibernateCriteria :

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();

这将在您当前的类上创建一个 criteria,并添加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天全站免登陆