package net.employee_managment.springboot.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
@Entity
@Table(name = "employee")
@Inheritance(strategy = InheritanceType.JOINED)
public class Employee {
@Id
@Column(name="employee_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private int employee_id;
@NotNull
@ManyToOne
@JoinColumn(name="general_details_id", nullable = false)
private GeneralDetails generalDetails;
@NotNull
@ManyToOne
@JoinColumn(name="spouse_id", nullable = false)
private Spouse spouse;
@NotNull
@ManyToOne
@JoinColumn(name="address_Id")
private Address[] addresses;
@NotNull
@ManyToOne
@JoinColumn(name="child_ID")
private Child[] children;
.... Constractors, Gettes, Setters}
Until now I could use the ID of the objects within the Employee object to link the objects and everything worked fine. But now I have an array of objects and I have a hard time figuring out how to link the Address array to the Employee object
CodePudding user response:
The @ManyToOne constraint implies a singular relationship on the side that owns the mapping. If you want to associate multiple objects on the owner side then you really need the inverse annotation (i.e @OneToMany) and I personally always tend to associate that annotation with either a List or Set implementation (any will do). Thus your member variable declaration would look as follows:
@NotNull
@OneToMany
private Set<Address> addresses;
This way you're able to pass your Employee instance a List (or Set in this case) of Address instances and providing you have update/insert cascade enabled (as well GeneratedId's), each Address in the collection will be automatically assigned id when the parent Employee instance is persisted.
To answer your follow up question:
Creating the json post from the client simply involves embedding the array of address objects in the parent JSON object, for example:
{
"generalDetails": 1,
"spouse": 2,
"addresses": [{
"street": "streetVal1",
"town": "townVal1",
"postCode": "pcVal1"
},
{
"street": "streetVal2",
"town": "townVal2",
"postCode": "pcVal2"
}]
}
You'll note that I do not specify and Id field on the address objects, this will be handled server-side as mentioned earlier for new addresses. For updates, then you would, of course, add the id field to each of the address objects. In any case, the JSON object structure would look exactly as I've outlined.