Как отправить объект JSON с массивом объектов в контроллер Spring?

0

У меня две модели домена, сопоставленные с использованием Hibernate @OneToMany. Я пытаюсь создать объект JSON во внешнем интерфейсе и отправить его на контроллер весны mvc, чтобы установить данные модели самостоятельно.

Ниже приведены мои модельные классы: ConceptModelDetails.java

@Entity
@Table(name="conceptModelDetails")
@SequenceGenerator(name="CONCEPT_SEQ",sequenceName="concept_sequence", initialValue=1, allocationSize=1)
public class ConceptModelDetails implements java.io.Serializable{
    private static final long serialVersionUID = 1L;
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="CONCEPT_SEQ")
    private int instructionsId;
    private String operationType;
    private String conceptModelID;
    private String requestor;
    private String status;
    private Timestamp requestDateTime;
    private Timestamp lastExecutedDateTime;
    private Timestamp completedDateTime;
    @OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="conceptModelDetails")
    @JsonManagedReference   // nested exception is org.springframework.http.converter.HttpMessageNotWritableException: 
    //Could not write JSON: Infinite recursion
//The fix is to get Jackson to be able to handle bi-directional references
    private List<Instructions> instructions = new ArrayList<Instructions>(); 




    public ConceptModelDetails() {
        // TODO Auto-generated constructor stub
    }


//setter & getter methods        
}

и Instructions.java:

@Entity
@Table(name="instructions")
@SequenceGenerator(name="INSTRUCTIONS_SEQ", sequenceName="instructions_sequence",initialValue=1, allocationSize=1)
public class Instructions implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="INSTRUCTIONS_SEQ")
    private int Sno;
    private String instruction;
    @ManyToOne
    @JoinColumn(name="instructionsId")
    @JsonBackReference
    private ConceptModelDetails conceptModelDetails;


    //setter & getter methods
}

Это мой метод отправки в интерфейсе для создания и отправки объекта JSON:

$scope.send = function() {
    console.log("test");
    var dataObj = {
        "operationType" : $scope.operationType,
        "conceptModelID" : $scope.conceptID,
        "requestor" : $scope.requestor,
        "status" : "new",
        "requestDateTime" : null,
        "lastExecutedDateTime" : null,
        "completedDateTime" : null,
        "instructions" : null

    };
    console.log(dataObj);
    dataObj.instructions = [];    
    console.log($scope.operations_publish);
    var ins = getSelected();
    for ( var i in ins) {
        var temp = {

            instruction : null,
            conceptModelDetails : null

        }
        temp.instruction = ins[i];
        dataObj.instructions.push(temp);
    }
    var response = $http.post(
            'PostService', dataObj);
    response.success(function(data, status, headers, config) {
        $scope.responseData = data;
    });
    response.error(function(data, status, headers, config) {
        alert("Exception details: " + JSON.stringify({
            data : data
        }));
    });
}

Следующий мой контроллер:

@RequestMapping(value = "/PostService", method = RequestMethod.POST)
public @ResponseBody String Test(@RequestBody ConceptModelDetails conceptModelDetails){
    ApplicationContext context = new ClassPathXmlApplicationContext(
            "applicationContext.xml");
    ConceptModelDAO obj = (ConceptModelDAO) context.getBean("objDAO");
    System.out.println("concept id: "+conceptModelDetails.getConceptModelID()+" "+ conceptModelDetails.getInstructionsId());
    System.out.println("instructions id: "+conceptModelDetails.getInstructions());
    // ConceptModelDAOImpl objDAO = new ConceptModelDAOImpl();
    obj.add(conceptModelDetails);
    Instructions instructions = new Instructions();
    System.out.println("dimba: " + instructions.getInstruction());
    ArrayList<Instructions> operations = (ArrayList<Instructions>) conceptModelDetails.getInstructions();
    for (int i = 0; i< operations.size(); i++ ) {
        instructions.setInstruction(operations.get(i).getInstruction());
        instructions.setConceptModelDetails(conceptModelDetails);
        obj.addInstructions(instructions);
    }
    return null;
}

Я получаю eror: 400 (Bad Request) из-за List<Instructions> instructions. Пожалуйста, предложите, как мне с этим справиться.

  • 0
    Не могли бы вы опубликовать трассировку стека для исключения, которое вы получите в журналах?
  • 0
    Покажите нам JSON, публикуемый также из пользовательского интерфейса.
Показать ещё 1 комментарий
Теги:
spring-mvc
hibernate

1 ответ

2
Лучший ответ

Я нашел проблему в этом коде. Как пояснил Bozho здесь,
ArrayList<Instructions> operations = (ArrayList<Instructions>) conceptModelDetails.getInstructions();

должно быть

List<Instructions> operations = conceptModelDetails.getInstructions(); в регуляторе пружины.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню