I\'ve got a following Java class which is also a Hibernate entity:
@Entity
@Table(name = \"category\")
public class Category {
@ManyToOne
@JoinColumn(na
You can define lazy init
@ManyToOne(fetch=FetchType.LAZY)
guess the column is nullable so it's not a problem to save the Category without parent (root)
There is one more solution to problem - using the default constructor of the entity you want a reference for and set id and version (if it is versioned).
Constructor<S> c = entityClass.getDeclaredConstructor();
c.setAccessible(true);
S instance = c.newInstance();
Fields.set(instance, "id", entityId.getId());
Fields.set(instance, "version", entityId.getVersion());
return instance;
We can use such an approach because we don't use lazy loading but instead have 'views' of entities which are used on the GUI. That allows us to get away from all the joins Hibernate uses to fill all eager relations. The views always have id and version of the entity. Hence, we can fill the reference by creating an object which would appear to Hibernate as not transient.
I tried both this approach and the one with session.load(). They both worked fine. I see some advantage in my approach as Hibernate won't leak with its proxies elsewhere in the code. If not properly used, I'll just get the NPE instead of the 'no session bound to thread' exception.
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()
.