本文介绍了标准的JPA方法来初始化懒惰实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JPA(Hibernate作为我的JPA提供者)。我真的试图避免休眠细节并使用JPA规范。我有一个初始化懒惰实体的函数。不幸的是,它使用Hibernate特定的功能。这是我的功能:

  private T initializeAndUnproxy(T entity){
if(entity == null){
抛出新
NullPointerException(初始化传递的实体为空);
}

Hibernate.initialize(entity);
if(entity instanceof HibernateProxy){
entity =(T)((HibernateProxy)entity).getHibernateLazyInitializer()。getImplementation();
}
返回实体;
}

是否有纯JPA方式来初始化实体?

解决方案

似乎没有一种标准的方式来初始化实体。

有一个标准的方法来检查实体是否被初始化(完全加载),并且这是通过(另请参阅的文章。



但是如果你真的需要通过一个标准框架方法完全初始化实体,那么不幸的是,似乎没有办法,你必须坚持Hibernate特定的代码现在。


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?

解决方案

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.

这篇关于标准的JPA方法来初始化懒惰实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:00