简体   繁体   中英

Question about entities in spring boot java

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

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 (ie @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.

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