Отображение "многие ко многим" и JSON выборка - PullRequest
0 голосов
/ 12 июля 2020

Я делаю небольшой проект, в котором будет два класса сущностей

  1. Ресурсы
  2. Проекты

Цель: один проект может иметь несколько Ресурсы (отдельные разработчики), а также один ресурс могут работать в нескольких проектах. Я использую jersey 2.29.1

Когда я пытаюсь запустить его напрямую, используя тестовый класс Utility, используя Publi c stati c void main. все работает нормально. Но в тот момент, когда я вставляю этот код в Jersy, чтобы получить ответ JSON. Это дает мне ошибку.

Единственное, что я мог понять, это то, что ошибка связана с сопоставлением, т.е. если я вызываю класс ресурсов из Postman, чтобы получить ответ JSON и помещаю аннотацию @JsonTransient в Список ресурсов в Project CLass. Он будет работать нормально. Но в тот момент, когда я вызываю объект Project, он не предоставит мне список ресурсов, тогда

package com.oracle.ProjectManagement.Entities;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.json.bind.annotation.JsonbTransient;
import javax.persistence.*;

@Entity(name="ProjectMaster" )
@Table(name= "project_master")
public class ProjectMaster {
     
    @GeneratedValue(strategy=GenerationType.IDENTITY)
     @Id
     @Column
     int Project_ID;
     
     @Column
     String Project_Name;
     
     @Column
     Date Start_Date;
     
     @Column
     Date End_Date;
     
     @Column
     int Onsite_Manager;
     
     @Column
     int Offshore_Manger;
     
     @Column
     int Client_ID;
     
     @Column
     String Description;
    
   
    @ManyToMany( cascade= CascadeType.ALL, mappedBy= "ProjectList")
    List<ResourceMaster> ResourseList = new ArrayList<ResourceMaster>();

    public int getProject_ID() {
        return Project_ID;
    }

    public void setProject_ID(int project_ID) {
        Project_ID = project_ID;
    }

    public String getProject_Name() {
        return Project_Name;
    }

    public void setProject_Name(String project_Name) {
        Project_Name = project_Name;
    }

    public Date getStart_Date() {
        return Start_Date;
    }

    public void setStart_Date(Date start_Date) {
        Start_Date = start_Date;
    }

    public Date getEnd_Date() {
        return End_Date;
    }

    public void setEnd_Date(Date end_Date) {
        End_Date = end_Date;
    }

    public int getOnsite_Manager() {
        return Onsite_Manager;
    }

    public void setOnsite_Manager(int onsite_Manager) {
        Onsite_Manager = onsite_Manager;
    }

    public int getOffshore_Manger() {
        return Offshore_Manger;
    }

    public void setOffshore_Manger(int offshore_Manger) {
        Offshore_Manger = offshore_Manger;
    }

    public int getClient_ID() {
        return Client_ID;
    }

    public void setClient_ID(int client_ID) {
        Client_ID = client_ID;
    }

    public String getDescription() {
        return Description;
    }

    public void setDescription(String description) {
        Description = description;
    }

    
    public List<ResourceMaster> getResourseList() {
        return ResourseList;
    }

    public void setResourseList(List<ResourceMaster> resourseList) {
        ResourseList = resourseList;
    }


    
}

и

package com.oracle.ProjectManagement.Entities;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.json.bind.annotation.JsonbTransient;
import javax.persistence.*;


@Entity(name= "ResourceMaster")
@Table(name = "Resource_master")

public class ResourceMaster {
    
    @Column
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int Resource_Id;
    
    @Column
    String  First_Name;
    
    @Column
    String  Last_name;
    
    @Column
    String  Short_Name;
    
    @Column
    String  Work_Location;
    
    @Column
    int  Manager_ID;
    
    @Column
    Date  Date_of_Joining;

    public int getResource_Id() {
        return Resource_Id;
    }

    public void setResource_Id(int resource_Id) {
        Resource_Id = resource_Id;
    }

    public String getFirst_Name() {
        return First_Name;
    }

    public void setFirst_Name(String first_Name) {
        First_Name = first_Name;
    }

    public String getLast_name() {
        return Last_name;
    }

    public void setLast_name(String last_name) {
        Last_name = last_name;
    }

    public String getShort_Name() {
        return Short_Name;
    }

    public void setShort_Name(String short_Name) {
        Short_Name = short_Name;
    }

    public String getWork_Location() {
        return Work_Location;
    }

    public void setWork_Location(String work_Location) {
        Work_Location = work_Location;
    }

    public int getManager_ID() {
        return Manager_ID;
    }

    public void setManager_ID(int manager_ID) {
        Manager_ID = manager_ID;
    }

    public Date getDate_of_Joining() {
        return Date_of_Joining;
    }

    public void setDate_of_Joining(Date date_of_Joining) {
        Date_of_Joining = date_of_Joining;
    }
    
    
    @ManyToMany(fetch = FetchType.EAGER,cascade= CascadeType.ALL)
    @JoinTable(name= "resource_project_map", joinColumns = @JoinColumn(name = "Resource_id"),
              inverseJoinColumns =  @JoinColumn(name = "Project_ID") )
    List<ProjectMaster> ProjectList = new ArrayList<ProjectMaster>();

    public List<ProjectMaster> getProjectList() {
        return ProjectList;
    }

    public void setProjectList(List<ProjectMaster> projectList) {
        ProjectList = projectList;
    }
    

}

ошибка

<code><!doctype html><html lang="en"><head><title>HTTP Status 500 – Internal Server Error</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 500 – Internal Server Error</h1><hr class="line" /><p><b>Type</b> Exception Report</p><p><b>Message</b> org.glassfish.jersey.server.ContainerException: java.lang.StackOverflowError</p><p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.StackOverflowError
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:408)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:346)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:365)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:318)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:205)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Причина

org.glassfish.jersey.server.ContainerException: java.lang.StackOverflowError
    org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:254)
    org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:236)
    org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:436)
    org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:261)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:248)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:244)
    org.glassfish.jersey.internal.Errors.process(Errors.java:292)
    org.glassfish.jersey.internal.Errors.process(Errors.java:274)
    org.glassfish.jersey.internal.Errors.process(Errors.java:244)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:232)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:680)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:392)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:346)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:365)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:318)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:205)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Причина

java.lang.StackOverflowError
    java.time.temporal.ValueRange.getMinimum(Unknown Source)
    java.time.temporal.ValueRange.isIntValue(Unknown Source)
    java.time.temporal.ValueRange.isValidIntValue(Unknown Source)
    java.time.temporal.ValueRange.checkValidIntValue(Unknown Source)
    java.time.temporal.ChronoField.checkValidIntValue(Unknown Source)
    java.time.LocalDate.ofEpochDay(Unknown Source)
    java.time.LocalDateTime.ofEpochSecond(Unknown Source)
    java.time.ZonedDateTime.create(Unknown Source)
    java.time.ZonedDateTime.ofInstant(Unknown Source)
    java.time.chrono.IsoChronology.zonedDateTime(Unknown Source)
    java.time.chrono.IsoChronology.zonedDateTime(Unknown Source)
    java.time.format.DateTimePrintContext.adjust(Unknown Source)
    java.time.format.DateTimePrintContext.&lt;init&gt;(Unknown Source)
    java.time.format.DateTimeFormatter.formatTo(Unknown Source)
    java.time.format.DateTimeFormatter.format(Unknown Source)
    org.eclipse.yasson.internal.serializer.AbstractDateTypeSerializer.formatDefault(AbstractDateTypeSerializer.java:51)
    org.eclipse.yasson.internal.serializer.AbstractDateTypeSerializer.formatDefault(AbstractDateTypeSerializer.java:28)
    org.eclipse.yasson.internal.serializer.AbstractDateTimeSerializer.toJson(AbstractDateTimeSerializer.java:77)
    org.eclipse.yasson.internal.serializer.AbstractDateTimeSerializer.serialize(AbstractDateTimeSerializer.java:52)
    org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:95)
    org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:92)
    org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:61)
    org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:63)
    org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:95)
    org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializeItem(AbstractContainerSerializer.java:141)
    org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:39)
    org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:27)
    org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:63)
    org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:95)
    org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:103)
    org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:61)
    
    ..
    .
    .
    .
    
    org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:63)
    org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:95)
    org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializeItem(AbstractContainerSerializer.java:141)

Примечание Полная трассировка стека root причина доступна в журналах сервера.

Apache Tomcat / 9.0.35

Пом. xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.oracle</groupId>
    <artifactId>ProjectManagement</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>ProjectManagement</name>

    <build>
        <finalName>ProjectManagement</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
        </dependency>
      
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-binding</artifactId>
        </dependency>
   
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>
            <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.3.7.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.common</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>5.0.4.Final</version>
    </dependency>   
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.30</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.30</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->


    </dependencies>
    <properties>
        <jersey.version>2.29.1</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

...