Consider an entity like so
public class SomeEntity {
@ManyToOne
@JoinColumn(name = "company_fk")
private CompanyEntity company;
}
The company_fk column is an integer. In my application I am frequently find myself in a situation where I have the company_fk integer but I don’t necessarily have the CompanyEntity.
What i want to do is to create a new instance of SomeEntity and associate it with CompanyEntity so I end up having to read the CompanyEntity from the db just so I can establish the relationship. This is not very good because I am going to the db even though I don’t need to do so.
Is there a way to avoid having to load an entity just to establish a relationship? I am using JPA 2 with Hibernate and I am open to using hibernate only mapping to make this work if there is way.
That’s exactly why
em.getReference()exists. It assumes the entity with the given ID exists, and returns a proxy to this entity:Hibernate’s native Session class has the same method, except it’s called
load().