Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently determining the IDs of entities referenced via OneToMany relationship

Tags:

java

hibernate

Let's say I have a Hibernate entity that declares a OneToMany relationship to a different entity:

@Entity
public class SomeEntity {
  @OneToMany(fetch = FetchType.LAZY)
  private List<OtherEntity> otherEntities = new LinkedList<OtherEntity>();

  [...]
}

When mapping SomeEntity to the corresponding DTO, all I need are the IDs that identify OtherEntity as primary key (i.e., I am not actually interested in OtherEntity instances).

Does Hibernate support this pattern, i.e., only retrieving the IDs of entities referenced via a OneToMany relationship?

I cannot influence how SomeEntity is retrieved (i.e., I have an existing SomeEntity instance retrieved within te scope of the current Hibernate session), but let's assume that lazy loading has not yet taken place, so just retrieving the child objects' IDs (rather than the complete objects) would actually yield a performance benefit.

like image 358
Thilo-Alexander Ginkel Avatar asked Nov 15 '11 14:11

Thilo-Alexander Ginkel


People also ask

What makes a one-to-many relationship as bidirectional relationship?

The way this works at the database level is we have a cart_id as a primary key in the cart table and also a cart_id as a foreign key in items. The way we do it in code is with @OneToMany. We can also add a reference to Cart in each Item using @ManyToOne, making this a bidirectional relationship.

Can a JPA entity have multiple OneToMany associations?

You can have multiple one-to-many associations, as long as only one is EAGER. But, even if you can use Set instead of List to bypass this MultipleBagFetchException , it's not a good thing to do because you'll end up with a Cartesian Product.

What is the use of @ManyToOne?

A ManyToOne relationship in Java is where the source object has an attribute that references another object, the target object. I.e. the rather typical Java case that one object holds a reference to another object. A ManyToOne relationship can be specified unidirectional.

What is the default mechanism for representing one-to-many unidirectional relationships in JPA?

As straightforward as it might be in a relational database, when it comes to JPA, the one-to-many database association can be represented either through a @ManyToOne or a @OneToMany association since the OOP association can be either unidirectional or bidirectional.


1 Answers

Well, if you only need the entities' ids and you want to be economical about it, when you get those entities from the database you should state in your query that you only want to get the ids of each entry, using projections, something like :

 SELECT Entity.id as entity FROM Entity WHERE ... 

This will return an array of objects of the same type as Entity's id field type.

like image 173
Shivan Dragon Avatar answered Sep 18 '22 02:09

Shivan Dragon