Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: How to get entity based on field value other than ID?

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).

like image 617
Neo Avatar asked Feb 20 '13 10:02

Neo


People also ask

Can a JPA entity without @ID?

More precisely, a JPA entity must have some Id defined. But a JPA Id does not necessarily have to be mapped on the table primary key (and JPA can somehow deal with a table without a primary key or unique constraint).

How do you indicate entity in JPA?

The JPA specification requires the @Entity annotation. It identifies a class as an entity class. You can use the name attribute of the @Entity annotation to define the name of the entity. It has to be unique for the persistence unit, and you use it to reference the entity in your JPQL queries.

Which method in JPA is used to retrieve the entity based on its primary keys?

The find() method used to retrieve an entity defined as below in the EntityManager interface. T find(Class<T> entityClass, Object primaryKey) – Returns entity for the given primary key. It returns null if entity is not found in the database.

Why Id is mandatory in JPA?

Id is required by JPA, but it is not required that the Id specified in your mapping match the Id in your database. For instance you can map a table with no id to a jpa entity. To do it just specify that the "Jpa Id" is the combination of all columns.


1 Answers

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.

like image 83
Raul Rene Avatar answered Sep 23 '22 21:09

Raul Rene