java hibernate entity: allow to set related object both by id and object itself

て烟熏妆下的殇ゞ 提交于 2019-12-03 02:32:08

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().

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.

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!