JAX-WS + Hibernate + JAXB:如何在编组期间避免使用LazyInitializationException

时间:2014-03-19 15:02:53

标签: java web-services hibernate jboss jaxb

我有一个JAX-WS应用程序,它返回从Hibernate Database后端(Oracle 10g或Oracle 11g)获取的数据对象。我使用javax.persistence.criteria.CriteriaQuery。它工作正常,除非该对象具有依赖性,对于某些特定查询不应返回该依赖性,例如:

@Immutable
@Entity
@Table(schema = "some_schema", name = "USER_VW")
public class User implements Serializable {

  ...

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "PRFL_ID")
  public Profile getProfile() {...}

  public void setProfile(Profile profile) {...}

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "SM_OTH_TP_ID")
  public SomeOtherType getSomeOtherType() {...}

  public void setSomeOtherType(SomeOtherType otherType) {...}

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "SM_DPND_ID)
  public SomeDependency getSomeDependency() {...}

  public void setSomeDependency(SomeDependency dependency) {...}

...
}

这是我的标准查询:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> criteria = cb.createQuery(User.class);
criteria.distinct(true);
Root<User> user = criteria.from(User.class);
Join<User, Profile> profileJoin = user.join("profile", JoinType.INNER);
user.fetch("someOtherType", JoinType.LEFT);
criteria.select(user);
Predicate inPredicate = profileJoin.get("profileType").in(types);
criteria.where(inPredicate);

注意:我没有获取SomeDependency属性。我不希望它被退回。

以下是UserServiceResponse类的定义:

@XmlRootElement(name = "UserServiceResponse", namespace = "...")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserServiceResponse", namespace = "...")
public class UserServiceResponse {

@XmlElementWrapper(name = "users")
@XmlElement(name = "user")
private final Collection<User> users;

...

然后JAXB发现Hibernate会话已经关闭。当它试图编组响应时,我得到以下异常:

Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164) [hibernate-core-4.2.7.SP1-redhat-3.jar:4.2.7.SP1-redhat-3]
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285) [hibernate-core-4.2.7.SP1-redhat-3.jar:4.2.7.SP1-redhat-3]
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185) [hibernate-core-4.2.7.SP1-redhat-3.jar:4.2.7.SP1-redhat-3]

    at com.myproject.model.user.entity.SomeDependency_$$_jvsteec_98.getCode(SomeDependency_$$_jvsteec_98.java)
...
    at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:494)
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:323)
    at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:251)
    at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:74) [jboss-jaxb-api_2.2_spec-1.0.4.Final-redhat-2.jar:1.0.4.Final-redhat-2]
    at org.apache.cxf.jaxb.JAXBEncoderDecoder.writeObject(JAXBEncoderDecoder.java:612) [cxf-rt-databinding-jaxb-2.7.7.redhat-1.jar:2.7.7.redhat-1]
    at org.apache.cxf.jaxb.JAXBEncoderDecoder.marshall(JAXBEncoderDecoder.java:240) [cxf-rt-databinding-jaxb-2.7.7.redhat-1.jar:2.7.7.redhat-1]
    ... 32 more

当marshaller试图获得&#34;代码&#34;的价值时,就会发生这种情况。 SomeDependency类的属性,它是一个HibernateProxy实例。

我现在看到的解决方案是添加某种&#34;过滤器&#34;在编组期间检查对象是否是HibernateProxy的实例。如果是HibernateProxy实例,则过滤器处理它,如果没有,则只保留其默认行为。

我该怎么做?使用XmlJavaTypeAdapter类?或者使用com.sun.xml.internal.bind.v2.runtime.reflect.Accessor?

如果有人能告诉我任何其他方法来解决我的问题,我将不胜感激。

注意:我重复使用相同的Hibernate代码和POJO,在其他Web服务中的JAX-WS内部以及应用程序的其他模块中的JAX-WS外部,其中延迟加载是一个优势。

更新

我尝试过使用XmlJavaTypeAdapter但它并不适合我。我创建了一个新的适配器 - HibernateProxyAdapter,它扩展了XmlJavaTypeAdapter。用户实体不是我唯一拥有的POJO,事实上,它们有很多。为确保将适配器应用于所有这些适配器,我将其添加到包级别。

@XmlJavaTypeAdapters(
    @XmlJavaTypeAdapter(value=HibernateProxyAdapter.class, type=HibernateProxy.class)
)
package com.myproject.model.entity;

这是适配器:

public class HibernateProxyAdapter extends XmlJavaTypeAdapter<Object, Object> {

    public Object unmarshal(Object v) throws Exception {
        return null; // there is no need to unmarshall HibernateProxy instances
    }

    public Object marshal(Object v) throws Exception {
        if (v != null) {
            if ( v instanceof HibernateProxy ) {
                LazyInitializer lazyInitializer = ((HibernateProxy) v ).getHibernateLazyInitializer();
                if (lazyInitializer.isUninitialized()) {
                    return null;
                } else {
                    // do nothing for now
                }
            } else if ( v instanceof PersistentCollection ) {
                if(((PersistentCollection) v).wasInitialized()) {
                    // got an initialized collection
                } else {
                    return null;
                }
            }
        }
        return v;
    }
}

现在我又得到了另一个例外:

Caused by: javax.xml.bind.JAXBException: class org.hibernate.collection.internal.PersistentSet nor any of its super class is known to this context.
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:588)
    at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:648)
    ... 57 more 

据我所知,当它试图编组一个初始化的hibernate集合时会发生这种情况,例如:org.hibernate.collection.internal.PersistentSet。我没有理由...... PersistentSet实现了Set接口。我以为JAXB应该知道如何处理它。有什么想法吗?

更新2: 我也尝试过使用Accessor类的第二个解决方案。这是我的访问者:

public class JAXBHibernateAccessor extends Accessor {

    private final Accessor accessor;

    protected JAXBHibernateAccessor(Accessor accessor) {
        super(accessor.getValueType());
        this.accessor = accessor;
    }

    @Override
    public Object get(Object bean) throws AccessorException {
        return Hibernate.isInitialized(bean) ? accessor.get(bean) : null;
    }

    @Override
    public void set(Object bean, Object value) throws AccessorException {
        accessor.set(bean, value);
    }
}

... AccessorFactory

public class JAXBHibernateAccessorFactory implements AccessorFactory {

    private final AccessorFactory accessorFactory = AccessorFactoryImpl.getInstance();

    @Override
    public Accessor createFieldAccessor(Class bean, Field field, boolean readOnly) throws JAXBException {
        return new JAXBHibernateAccessor(accessorFactory.createFieldAccessor(bean, field, readOnly));
    }

   @Override
   public Accessor createPropertyAccessor(Class bean, Method getter, Method setter) throws JAXBException {
        return new JAXBHibernateAccessor(accessorFactory.createPropertyAccessor(bean, getter, setter));
   }
}

package-info.java ...

@XmlAccessorFactory(JAXBHibernateAccessorFactory.class)
package com.myproject.model.entity;

现在我需要在JAXB上下文中启用自定义AccessorFactory / Accessor支持。我尝试将自定义JAXBContextFactory添加到Web服务定义中,但它没有工作......

@WebService
@UsesJAXBContext(JAXBHibernateContextFactory.class)
public interface UserService {
...
}

这是我的contextFactory

public class JAXBHibernateContextFactory implements JAXBContextFactory {

    @Override
    public JAXBRIContext createJAXBContext(@NotNull SEIModel seiModel, @NotNull List<Class> classes,
                                       @NotNull List<TypeReference> typeReferences) throws JAXBException {
        return ContextFactory.createContext(classes.toArray(new Class[classes.size()]), typeReferences,
            null, null, false, new RuntimeInlineAnnotationReader(), true, false, false);
    }
}

我不知道为什么但是从不调用createJAXBContext方法。看起来@UsesJAXBContext注释什么都不做......

有谁知道如何让它发挥作用? 或者我如何设置&#34; com.sun.xml.bind.XmlAccessorFactory&#34;在JAX-WS中JAXBContext属性为true?

BTW,我忘了提及,我将它部署到JBoss EAP 6.2。

3 个答案:

答案 0 :(得分:2)

我认为注释@XmlTransient就是为了这个。将其添加到您的属性someDependency,以使JAXB忽略此字段。

@XmlTransient
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SM_DPND_ID)
public SomeDependency getSomeDependency() {...}

更新以下评论:如果您必须选择适配器选项,我猜您必须:

  1. 为实体用户扩展XmlAdapter
  2. 创建新适配器
  3. 在适配器中为每个属性调用marshaller并使用方法Hibernate.isInitialized(yourObject.getSomeDependency())来测试是否在调用marshaller之前加载了关联。
  4. 通过向您的实体用户
  5. 添加具有适当属性的@XmlJavaTypeAdapter来声明它

    也许可以通过直接为属性someDependency创建适配器来完成,但是当JAXB尝试将属性传递给适配器时,您可能会发生LazyInitializationException。

答案 1 :(得分:1)

有两个解决方案可以合并,以便最好地控制编组。

  • 提供一个AccessorFactory,它将创建一个自定义Accessor。在此Accessor中,您可以覆盖

public abstract ValueT get(BeanT bean) throws AccessorException;

如果pojo未初始化,则返回null:

if (!Hibernate.isInitialized(valueT)) { return null; }

请注意,有一种烦人的优化方法:

public Accessor<BeanT,ValueT> optimize(@Nullable JAXBContextImpl context) { return this; }

可以替换您的自定义Accessor,具体取决于您覆盖的Accessor(请参阅FieldReflection)。

这是有问题的解决方案之一,但我想您忘记了以下JAXBContext的初始化:

HashMap<String, Object> props = new HashMap<String, Object>(); props.put(JAXBRIContext.XMLACCESSORFACTORY_SUPPORT, true); JAXBContext jaxbContext = JAXBContext.newInstance(new Class[] { clazz }, props);

  • 第二个解决方案是覆盖JAXB的AnnotationReader,这样你就可以返回你想要的注释,具体取决于Class,Field等......所以你可以返回XmlTransient注释,如果你不希望你的对象是整理。 这是这样做的:

HashMap<String, Object> props = new HashMap<String, Object>(); props.put(JAXBRIContext.ANNOTATION_READER, new CustomAnnotationReader()); JAXBContext jaxbContext = JAXBContext.newInstance(new Class[] { clazz }, props);

RuntimeInlineAnnotationReader是最终版,无法覆盖...因此您必须复制代码。

我个人合并了这两个approches,以便根据对象的上下文和内容修改编组。

答案 2 :(得分:1)

使用Javaassist简单地替换Accessor $ FieldReflection的实现来绕过这个:

static {
  ClassPool pool = ClassPool.getDefault();
  try {
     CtClass cc = pool.get("com.sun.xml.bind.v2.runtime.reflect.Accessor$FieldReflection");
     CtMethod method = cc.getMethod("get", "(Ljava/lang/Object;)Ljava/lang/Object;");
     method.insertBefore("if (bean instanceof org.hibernate.proxy.HibernateProxy) {\n"
              + "bean = ((org.hibernate.proxy.HibernateProxy)bean).getHibernateLazyInitializer().getImplementation();\n"
              + "}");
    cc.toClass();
  }
  catch (Throwable t) {
      t.printStackTrace();
  }
}