Standard JPA method to initialize lazy entity

2020-07-06 06:08发布

I am using JPA (Hibernate as my JPA provider). I am really trying to avoid hibernate specifics and use the JPA specifications. I have a function that initializes lazy entities. Unfortunately, It uses Hibernate specific functions. This is my function:

private T initializeAndUnproxy(T entity) {
        if (entity == null) {
            throw new 
               NullPointerException("Entity passed for initialization is null");
        }

        Hibernate.initialize(entity);
        if (entity instanceof HibernateProxy) {
            entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer().getImplementation();
        }
        return entity;
    }

Is there any pure JPA way to initialize entities?

1条回答
家丑人穷心不美
2楼-- · 2020-07-06 06:39

There doesn't seem to be a standard way to initialize entities.

There is a standard way to check if entities are initialized (fully loaded) or not, and that's via PersistenceUnitUtil (also see How to test whether lazy loaded JPA collection is initialized?)

As long as the entity is still attached, you can access its properties to force initialization. This isn't very neat, but does work to some extend. The downside is that depending on the exact nature of the properties (e.g. a collection with many elements), you may fire tens, to hundreds or even many thousands of queries to your database.

In many cases you'll be better of to specify upfront what needs to be initialized instead of force initializing (unknown) entities programmatically. I wrote an article about this here.

But if you really need to fully initialize entities with a single call to some standard framework method, then unfortunately there doesn't seem to be a way and you'll have to stick to Hibernate specific code for now.

查看更多
登录 后发表回答