简体   繁体   中英

How to deserialize Hibernate entity from JSON (Jackson) without creating DTO object

I have a webapp that has been using Hibernate for persistence. Recently, a requirement was added that would require us to recieve entities over JSON deserialize them, then persist them.

The problem lies in that the entity class uses Hibernate's object references for @ManyToOne relationships. For instance, my entity object looks like this (fake example):

public class Student {
    @Id private int student_id;
    @Column private String name;
    @ManyToOne private School school;
    @OneToMany private List<Assignment> assignments;
}

public class School {
    @Id private int school_id;
    @Column private String name;
}

public class Assignment {
    @Id private int assignment_id;
    @Column private String name;
    @Column private int grade;
}

My Student table has columns student_id , name , and school_id . My Assignment table has columns assignment_id , name and grade .

However, I'm not sure how to structure the JSON to send to the server. Let's say I am trying to create a new Student, with new Assignments, enrolled in an existing School.

Ideally, the JSON should look like:

{
    "name": "vikarjramun",
    "age": 23,
    "school_id": 1893,
    "assignments": [
        { "name": "Math", "grade": 100 },
        { "name": "Science", "grade": 93 }      
    ]
}

However, if I use Jackson on the current entities, the JSON must be structured as follows:

{
    "name": "vikarjramun",
    "age": 23,
    "school": { "school_id": 1983 }
    "assignments": [
        { "name": "Math", "grade": 100 },
        { "name": "Science", "grade": 93 }      
    ]
}

When I try to persist the resultant object, it will then complain that the School already exists in the database (ConstraintViolationException).

I don't mind changing the format of the JSON, I just want to somehow get an object that can be directly persisted into the database. Will I need to write a custom deserializer? How else can I accomplish this?

Thanks

Constraint violation usually occurs when you try to insert a duplicate entry that is already available in table.

If the primary key of the student table is auto generated means then this is the JSON payload you need to send to create student object.

{ "name": "vikarjramun",
 "school": { "school_id": 1983 }, "assignments": [ { "name": "Math", "grade": 100 }, { "name": "Science", "grade": 93 } ] }

In the @ManyToOne mapping please also add @JoinColumn("school_id);

This makes new column contains the primary key of the students table.

Where school_id is foreign key in student that link to school table primary key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM