双向ManyToOne关系NOT SPRING的EAP EAP 7.3的JPA +休眠REST序列化

问题描述

我来自Payara / EclipseLink背景,可以直接使用。我的合同要求我使用不支持EclipseLink.persistance的EAP,并且我总是更喜欢“提供”而不是添加库。

我正在为对象创建具有非常简单关系的非常简单的REST微服务。但是,当我尝试访问对象时,出现序列化错误(下面有详细说明)。

实体1

@Entity
@Table(name = "training_centers")
@NamedQuery(name = TrainingCenterEntity.findAll,query = "SELECT c FROM TrainingCenterEntity c")
@JsonbVisibility(PrivateVisibilityStrategy.class)
public class TrainingCenterEntity implements Serializable,ValidEntity {

    private static final long serialVersionUID = 9197911968578298904L;
    public static final String PREFIX = "centers.entity.TrainingCenter.";
    public static final String findAll = PREFIX + "findAll";

    @Id
    @Column(name = "program_code")
    private String program_code;

    @Column(name = "program_name",length = 255,nullable = false)
    private String program_name;

    public TrainingCenterEntity(String code,String name) {
        this.program_code = code;
        this.program_name = name;
        this.classifications = new ArrayList<ClassificationEntity>();
    }
    
    public TrainingCenterEntity() {
        this.classifications = new ArrayList<ClassificationEntity>();
    }

    public String getProgramCode() {
        return program_code;
    }

    public void setProgramCode(String program_code) {
        this.program_code = program_code;
    }
    
    @OnetoMany(
            fetch = FetchType.LAZY,cascade = CascadeType.ALL,orphanRemoval = true,mappedBy = "center")
    private List<ClassificationEntity> classifications;

两个实体

@Entity
@Table(name = "classifications")
@NamedQueries({
    @NamedQuery(name = ClassificationEntity.findByProgramCode,query = "SELECT c FROM ClassificationEntity c WHERE c.center = :programCode"),@NamedQuery(name = ClassificationEntity.findAll,query = "SELECT c FROM ClassificationEntity c")
})
@JsonbVisibility(PrivateVisibilityStrategy.class)
public class ClassificationEntity implements Serializable,ValidEntity{
    
    private static final long serialVersionUID = 5138672261884252346L;
    public static final String PREFIX = "centers.entity.ClassificationEntity.";
    public static final String findByProgramCode = PREFIX + "findByProgramCode";
    public static final String findAll = PREFIX + "findAll";

    @Id
    @Column(name = "classification_id",columnDeFinition = "serial")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name = "classification_type",unique = true,nullable = false)
    private ClassificationType classificationType;
    
    @Column(name = "classification_name",nullable = true,length = 255)
    private String classificationName;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "program_code",referencedColumnName = "program_code")
    private TrainingCenterEntity center;
    
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public ClassificationEntity() {
        this.center = new TrainingCenterEntity();
    }

实体1的结束点

@GET
@Produces({MediaType.APPLICATION_JSON})
public List<TrainingCenterEntity> findAll() {
    return this.manager.findAll();
}

用于REST端点的StackTrace

11:44:03,129 SEVERE [org.eclipse.yasson.internal.Marshaller] (default task-1) Unable to serialize property 'classifications' from ptsi.service.centers.entity.TrainingCenterEntity
11:44:03,129 SEVERE [org.eclipse.yasson.internal.Marshaller] (default task-1) Generating incomplete JSON
11:44:03,129 INFO  [io.jaegertracing.internal.reporters.LoggingReporter] (default task-1) Span reported: 33fb13e2e5f679d8:33fb13e2e5f679d8:0:1 - GET:ptsi.service.centers.boundary.TrainingCenterResource.findAll
11:44:03,129 ERROR [io.undertow.request] (default task-1) UT005023: Exception handling request to /learning-hibernate/api/centers: org.jboss.resteasy.spi.UnhandledException: javax.ws.rs.ProcessingException: RESTEASY008205: JSON Binding serialization error javax.json.bind.JsonbException: Unable to serialize property 'classifications' from ptsi.service.centers.entity.TrainingCenterEntity
    at [email protected]//org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:356)
    at [email protected]//org.jboss.resteasy.core.Synchronousdispatcher.writeException(Synchronousdispatcher.java:193)
    at [email protected]//org.jboss.resteasy.core.Synchronousdispatcher.writeResponse(Synchronousdispatcher.java:539)
    at [email protected]//org.jboss.resteasy.core.Synchronousdispatcher.invoke(Synchronousdispatcher.java:461)
    at [email protected]//org.jboss.resteasy.core.Synchronousdispatcher.lambda$invoke$4(Synchronousdispatcher.java:229)
    at [email protected]//org.jboss.resteasy.core.Synchronousdispatcher.lambda$preprocess$0(Synchronousdispatcher.java:135)
    at [email protected]//org.jboss.resteasy.core.interception.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:356)
    at [email protected]//org.jboss.resteasy.core.Synchronousdispatcher.preprocess(Synchronousdispatcher.java:138)
    at [email protected]//org.jboss.resteasy.core.Synchronousdispatcher.invoke(Synchronousdispatcher.java:215)
    at [email protected]//org.jboss.resteasy.plugins.server.servlet.ServletContainerdispatcher.service(ServletContainerdispatcher.java:227)
    at [email protected]//org.jboss.resteasy.plugins.server.servlet.HttpServletdispatcher.service(HttpServletdispatcher.java:56)
    at [email protected]//org.jboss.resteasy.plugins.server.servlet.HttpServletdispatcher.service(HttpServletdispatcher.java:51)
    at [email protected]//javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
    at [email protected]//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
    at [email protected]//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
    at io.opentracing.contrib.opentracing-jaxrs2//io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:52)
    at [email protected]//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at [email protected]//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at [email protected]//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at [email protected]//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at [email protected]//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
    at [email protected]//io.undertow.servlet.handlers.ServletdispatchingHandler.handleRequest(ServletdispatchingHandler.java:36)
    at [email protected]//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
    at [email protected]//io.undertow.servlet.handlers.security.SSL@R_626_404[email protected](SSL@R_626_404[email protected]:132)
    at [email protected]//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at [email protected]//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at [email protected]//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at [email protected]//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at [email protected]//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at [email protected]//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//io.undertow.servlet.handlers.ServletinitialHandler.handleFirstRequest(ServletinitialHandler.java:269)
    at [email protected]//io.undertow.servlet.handlers.ServletinitialHandler.access$100(ServletinitialHandler.java:78)
    at [email protected]//io.undertow.servlet.handlers.ServletinitialHandler$2.call(ServletinitialHandler.java:133)
    at [email protected]//io.undertow.servlet.handlers.ServletinitialHandler$2.call(ServletinitialHandler.java:130)
    at [email protected]//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at [email protected]//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at [email protected]//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1541)
    at [email protected]//io.undertow.servlet.handlers.ServletinitialHandler.dispatchRequest(ServletinitialHandler.java:249)
    at [email protected]//io.undertow.servlet.handlers.ServletinitialHandler.access$000(ServletinitialHandler.java:78)
    at [email protected]//io.undertow.servlet.handlers.ServletinitialHandler$1.handleRequest(ServletinitialHandler.java:99)
    at [email protected]//io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
    at [email protected]//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
    at [email protected]//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at [email protected]//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: javax.ws.rs.ProcessingException: RESTEASY008205: JSON Binding serialization error javax.json.bind.JsonbException: Unable to serialize property 'classifications' from ptsi.service.centers.entity.TrainingCenterEntity
    at org.jboss.resteasy.resteasy-json-binding-provider@3.11.2.Final-redhat-00002//org.jboss.resteasy.plugins.providers.jsonb.JsonBindingProvider.writeto(JsonBindingProvider.java:160)
    at [email protected]//org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext.writeto(AbstractWriterInterceptorContext.java:137)
    at [email protected]//org.jboss.resteasy.core.interception.ServerWriterInterceptorContext.writeto(ServerWriterInterceptorContext.java:61)
    at [email protected]//org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:124)
    at [email protected]//org.jboss.resteasy.security.doseta.DigitalSigningInterceptor.aroundWriteto(DigitalSigningInterceptor.java:147)
    at [email protected]//org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:129)
    at [email protected]//org.jboss.resteasy.core.ServerResponseWriter.lambda$writeNomapResponse$2(ServerResponseWriter.java:151)
    at [email protected]//org.jboss.resteasy.core.interception.ContainerResponseContextImpl.filter(ContainerResponseContextImpl.java:398)
    at [email protected]//org.jboss.resteasy.core.ServerResponseWriter.executeFilters(ServerResponseWriter.java:219)
    at [email protected]//org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:95)
    at [email protected]//org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:69)
    at [email protected]//org.jboss.resteasy.core.Synchronousdispatcher.writeResponse(Synchronousdispatcher.java:530)
    ... 58 more
Caused by: javax.json.bind.JsonbException: Unable to serialize property 'classifications' from ptsi.service.centers.entity.TrainingCenterEntity
    at [email protected]//org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:67)
    at [email protected]//org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
    at [email protected]//org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:96)
    at [email protected]//org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializeItem(AbstractContainerSerializer.java:157)
    at [email protected]//org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:39)
    at [email protected]//org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:27)
    at [email protected]//org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
    at [email protected]//org.eclipse.yasson.internal.Marshaller.serializeRoot(Marshaller.java:148)
    at [email protected]//org.eclipse.yasson.internal.Marshaller.marshall(Marshaller.java:76)
    at [email protected]//org.eclipse.yasson.internal.Marshaller.marshall(Marshaller.java:102)
    at [email protected]//org.eclipse.yasson.internal.JsonBinding.toJson(JsonBinding.java:118)
    at org.jboss.resteasy.resteasy-json-binding-provider@3.11.2.Final-redhat-00002//org.jboss.resteasy.plugins.providers.jsonb.JsonBindingProvider.writeto(JsonBindingProvider.java:156)
    ... 69 more
Caused by: org.hibernate.LazyInitializationException: Failed to lazily initialize a collection of role: ptsi.service.centers.entity.TrainingCenterEntity.classifications,Could not initialize proxy - no Session
    at [email protected]//org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:602)
    at [email protected]//org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:217)
    at [email protected]//org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:581)
    at [email protected]//org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:148)
    at [email protected]//org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:390)
    at [email protected]//org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:38)
    at [email protected]//org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:27)
    at [email protected]//org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:64)
    at [email protected]//org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:96)
    at [email protected]//org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:110)
    at [email protected]//org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:65)
    ... 80 more

另一侧出现相同的错误。使用EclipseLink时,这是开箱即用的,我已经尝试了几天,但是我看到的每个示例似乎都无法解决我的特定问题。

对于清晰度,这是ENTITY ONE的边界代码

一个实体的资源

@Stateless
@Path("centers")
public class TrainingCenterResource {
    
    @Inject
    TrainingCenterManager manager;

    // POST should return 201 with Location URI in header
    @POST
    @Consumes({MediaType.APPLICATION_JSON})
    public Response save(TrainingCenterEntity center,@Context UriInfo info) {
        TrainingCenterEntity saved = this.manager.save(center);
        String id = saved.getProgramCode();
        URI uri = info.getAbsolutePathBuilder().path("/" + id).build();
        return Response.created(uri).build();
    }

    @GET
    @Path("{id}")
    @Produces({MediaType.APPLICATION_JSON})
    public Response find(@PathParam("id") String id) {
        TrainingCenterEntity center = this.manager.findById(id);
        if (center != null) {
            return Response.ok(center).build();
        }
        else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }
    
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public List<TrainingCenterEntity> findAll() {
        return this.manager.findAll();
    }

    @PUT
    @Path("{id}")
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces({MediaType.APPLICATION_JSON})
    public TrainingCenterEntity update(@PathParam("id") String id,TrainingCenterEntity center) {
        center.setProgramCode(id);
        return this.manager.save(center);
    }

    @DELETE
    @Path("{id}")
    public void delete(@PathParam("id") String id) {
        this.manager.delete(id);
    }
}

一个实体的持久性管理器

@Stateless
public class TrainingCenterManager {

    @Inject
    private Logger LOGGER;

    @Inject
    private EntityManager em;

    
    public TrainingCenterEntity save(TrainingCenterEntity center) {
        try {
            return this.em.merge(center);
        } catch (PersistenceException pex) {
            LOGGER.log(Level.FINE,pex.toString(),pex);
            return null;
        }
    }
    
    public TrainingCenterEntity findById(String code) {
        try {
            return this.em.find(TrainingCenterEntity.class,code);
        } catch (Exception e) {
            LOGGER.log(Level.FINE,e.toString(),e);
            return null;
        }
    }
    
    public List<TrainingCenterEntity> findAll() {
        try {
            return this.em.createNamedQuery(TrainingCenterEntity.findAll,TrainingCenterEntity.class).getResultList();
        } catch (Exception e) {
            LOGGER.log(Level.FINE,e);
            return null;
        }
    }
    
    public void delete(String code) {
        try {
            TrainingCenterEntity reference = this.em.getReference(TrainingCenterEntity.class,code);
            this.em.remove(this.em.merge(reference));
        } catch (PersistenceException pex) {
            LOGGER.log(Level.FINE,pex);
        }
    }
}

解决方法

根据规范,您的经理EJB找到所有实体,然后将其加载到返回的List中,但是JPA默认将列表(例如,您实体中的分类)作为懒加载字段。

当findAll方法返回时,不再有任何事务,并且列表中的实体与EntityManager 分离。因此,实体管理器无法加载每个分类字段的内容以允许序列化。

您可以使用一些内部属性来更改实体管理器的行为,甚至将分类字段定义为渴望获取,但是当您使用TrainingCenterEntity而不访问分类字段时,这可能会引起性能问题(分类将从数据库中检索每次您获得中心位置。

您最好的方法是将命名查询更改为使用JOIN FETCH:

@NamedQuery(name = TrainingCenterEntity.findAll,query = "SELECT c FROM TrainingCenterEntity c JOIN FETCH c.classifications")

JOIN FETCH使JPA渴望获取原本懒加载字段的内容。

请注意:

  • 任何findAll方法都倾向于公开大量数据;和
  • JSON序列化库的某些实现不够智能,无法检测到循环关系,因此如果未正确标注为序列化忽略,分类-> trainingcenter可能会导致堆栈溢出(在Jackson情况下为@JsonIgnore)。

使用EclipseLink,您的代码可以正常工作,这可能是因为您的实体不是static weaved事先执行的。 EclipseLink的一些默认配置还允许在某些不同的情况下加载延迟字段,即使使用静态编织的延迟加载定义也是如此。在休眠状态下,编织称为bytecode enhancement,它是自动完成的。