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

前端 未结 3 1392
野趣味
野趣味 2021-02-05 17:18

I\'ve got a following Java class which is also a Hibernate entity:

@Entity
@Table(name = \"category\")
public class Category {

    @ManyToOne
    @JoinColumn(na         


        
3条回答
  •  滥情空心
    2021-02-05 18:14

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

提交回复
热议问题