重新附加实体以延迟加载集合(JPA / Hibernate)

时间:2014-01-21 12:18:35

标签: java hibernate jpa persistence entitymanager

任何人都可以帮我解决一个我认为很简单的JPA问题。我正在尝试在我的JPA持久性框架中编写一个通用的延迟加载管理器,因此应用程序堆栈中的更高层可以访问延迟加载的数据,而无需处理具体细节。

我有一个懒惰的加载管理器:

public class JpaLazyLoader extends AbstractJpaDAO<Void> implements LazyLoader
{

  public JpaLazyLoader()
  {
    super( void.class ); 
  }

  @Transactional(readOnly=true)
  public <T,E> T get( ILazyGetter<T,E> p_getter ) throws Exception {
    // reattach the object to the session

    E l_entity = getEntityManager().merge( p_getter.getEntity() );

    // return the getter data
    return p_getter.get( l_entity );
  }
}

懒惰的吸气器是这样的:

public interface ILazyGetter<T,E> extends Serializable
{
  public E getEntity();
  public T get( E p_entity ) throws Exception;
}

这个想法是它会像这样使用:

          return m_lazyLoader.get( new ILazyGetter<Collection<Child>, Parent>() {

            private static final long serialVersionUID = 1L;

            public Parent getEntity() {
              return getValue(); // get the parent object from somewhere
            }

            public Collection<Child> get( Parent p_entity ) throws Exception {
              // children are a lazy-loaded Set<Child>
              return p_entity.getChildren();
            }
          } );

Parent中的注释是这样的:

@Entity(name="parent")
public class Parent implements Serializable {

  private static final long serialVersionUID = 1L;

  ....

  @Id
  @Column(name="id")
  @GeneratedValue(strategy=GenerationType.AUTO)
  protected Long id;

  @OneToMany
  @JoinTable
  (
      name="parent_child_associations",
      joinColumns={ @JoinColumn(name="parent_id", referencedColumnName="id") },
      inverseJoinColumns={ @JoinColumn(name="child_id", referencedColumnName="id", unique=true) }
  )
  protected Set<Child> children;

}

父对象在另一个事务中加载,然后分离。我希望将父级重新连接到另一个会话(在@transactional位内)是一件微不足道的事情,但我无法让它工作。我在合并之前和之后尝试过乐观/悲观/无锁定,但似乎都没有。

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: test.Parent.children, could not initialize proxy - no Session
 at     org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
 at     org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
 at     org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
 at     org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)
 at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:180)

这是错误的做事方式吗?如果是这样,那么“正确”的方式是什么?如果没有,我做错了什么?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

好的,谢谢Andre,我已经开始工作了。

我根本没有初始化集合对象,而只是调用了parent.getChildren(),它只返回代理对象而不是强制获取。

对于有类似需求的人来说,更新的get方法如下:

@Transactional(readOnly=true)
public <T,E> T get( ILazyGetter<T,E> p_getter ) throws Exception {
  // reattach the object to the session    
  E l_entity = getEntityManager().merge( p_getter.getEntity() );

  T l_lazyData = p_getter.get( l_entity );

  // Just getting the data doesn't necessarily initialize it - 
  // explicitly initialize it depending on the data type.
  intializeEntity( l_lazyData );

  // return the getter data
  return l_lazyData;
}

/**
 * Attempt to initialize the entity so it is fully lazy loaded while in the transaction
 * @param p_entity
 */
protected void intializeEntity( Object p_entity ) {
  if( p_entity != null && p_entity instanceof Collection ) {
    Collection<?> l_entity = (Collection<?>)p_entity;
    l_entity.size(); // force the collection to load
  }
}