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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With