2

I want to send a JSON as POST Request to insert into the database. Following is the JSON

{
    "url": "https://www.tec.com",
    "status":"Regular",
     "Student": 
     {
         "id": 1,
         "name": "John Doe",
         "age": 12      
    }
}

where I have the main class

Data.java

@ToString
@Setter
@Getter
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "data")
public class Data implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int id;
    private String url;
    private String status;

    @ElementCollection
    private Student student;
}

Student.java


@ToString
@Setter
@Getter
@AllArgsConstructor
@Entity
@NoArgsConstructor
@Table(name = "Student")
public class Student implements Serializable {
    @Id
    private int id;
    private String name;
    private int age;
}

Please tell me how to resolve this .So that the data should save in the database when I send the JSON on the above-specified format.

Lutzi
  • 416
  • 2
  • 13
Lily
  • 605
  • 3
  • 15
  • 31
  • 1
    https://stackoverflow.com/questions/44258541/illegal-attempt-to-map-a-non-collection-as-a-onetomany-manytomany-or-collec/44259547 – trim24 Jan 25 '20 at 13:48
  • @trim24 i have also read this article as you have shared. But it doesn't make any sense to me. Please answer as per my scenario. – Lily Jan 25 '20 at 14:07
  • It is probably the same scenario, Can you trying replacing with `Set` ? – trim24 Jan 25 '20 at 14:11

1 Answers1

3

You are getting this error message because you placed the @ElementCollection annotation on student.

This annotation is meant for collections. It is meant to be placed on entity members which are collections such as a Set, List, etc.

You should remove this annotation from student and replace it with @OneToOne

public class Data implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int id;
    private String url;
    private String status;

    @OneToOne(cascade=CascadeType.ALL)
    private Student student;
}

@OneToOne means there is one Student for every one Data (cascade=CascadeType.ALL) means if you save Data, its student will also be saved.

Another option is to replace the single student with a collection of students.

Gonen I
  • 5,576
  • 1
  • 29
  • 60
  • The data is not being saved to the table `Student` if I removed `@ElementCollection`. Please update your answer with code how could I do so. – Lily Feb 09 '20 at 16:04
  • Sir the what should be the `GenerationType` of the @id in `Student` because I want to make the **ID** of `Data` and `Student` same .? – Lily Feb 09 '20 at 17:17
  • One easy way to make sure they are the same is to set the id yourself. Keep `@Id` and remove `@GeneratedValue`, then just set the id member yourself. – Gonen I Feb 09 '20 at 18:20