I\'ve got a following Java class which is also a Hibernate entity:
@Entity
@Table(name = \"category\")
public class Category {
@ManyToOne
@JoinColumn(na
Hibernate provides a method called (quite confusingly) Session.load() for this scenario.
Session.load() returns a lazy proxy with the given identifier without querying the database (if object with the given identifier is already loaded in the current Session, it returns an object itself).
You can use that proxy to initialize relationships in your entities being saved:
category.setParent(session.load(Category.class, parent_id));
Note that this code doesn't check existence of Category with the given id. However, if you have a foreign key constraint in your DB schema, you'll get a constraint violation error when invalid id is passed in.
JPA equivalent of this method is called EntityManager.getReference().