简体   繁体   中英

How to add multiple entity in a single entity in jpa spring boot application

I am trying to add multiple entities in a single entity, I don't know this way possible or not please refer to my below code and help

the below code are the entity tables

    @Entity 
    @Table(name = "agent_employee")
    public class AgentEmployee extends Agent implements Serializable{
    private static final long serialVersionUID = 1L;

    @OneToMany // unidirectional
    @JoinColumn(name = "employment_id", referencedColumnName = "id")
    List<Employment> employmnet = new ArrayList<Employment>();

    @OneToMany(
            mappedBy = "agent", 
            cascade = CascadeType.ALL,
            orphanRemoval = true
            )
    private Set<Officess> officess = new HashSet<>();

    public List<Employment> getEmploymnet() {
        return employmnet;
    }

    public void setEmploymnet(List<Employment> employmnet) {
        this.employmnet = employmnet;
    }

    public Set<Officess> getOfficess() {
        return officess;
    }

    public void setOfficess(Set<Officess> officess) {
        this.officess = officess;
    }
}

and Employment class is

@Data
@Entity
public class Employment {

@Id
@Column(nullable = false, unique = true)
private Long id;

private String empName;

private String location;

@Override
public String toString() {
    return "Employment [id=" + id + ", empName=" + empName + ", location=" + location + "]";
}

}

and Offices class is

@Data
@Entity
@Table(name = "officess")
public class Officess implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String officeName;

@ManyToOne
@JoinColumn(name = "agent_emp")
private AgentEmployee agent;   

}

And I have used spring boot repositories to all the respective entities

@GetMapping(path = "/add")
public @ResponseBody String addAgentEmployee() {
    try {
        AgentEmployee agemp = new AgentEmployee();
        agemp.setFirstName("harish");
        agemp.setLastName("kadsuru");
        agemp.setEmail("hari**********is.net");
        Employment emp1 = new Employment();
        Employment emp2 = new Employment();
        Employment emp3 = new Employment();
        emp1.setId(501l);
        emp2.setId(502l);
        emp3.setId(503l);
        emp1.setEmpName("junior engineer");
        emp2.setEmpName("senior engineer");
        emp3.setEmpName("team leader");
        emp1.setLocation("bengaluru");
        emp2.setLocation("mumbai");
        emp3.setLocation("UAE");
        List<Employment> emps = Arrays.asList(emp1, emp2, emp3);
        employmentRepository.saveAll(emps);
        agemp.setEmploymnet(emps);
        agentEmployeeRepository.save(agemp);
        return "saved";
    } catch (Exception e) {
        return "unable to save data due to exception";
    }

}

@GetMapping("addOffice")
public @ResponseBody String addAgentEmployeeOffice() {

    AgentEmployee emp;
    Optional<AgentEmployee> agemp = agentEmployeeRepository.findById(27l);
    if (agemp.isPresent()) {
        emp = agemp.get();
    }
    else {
        emp =new AgentEmployee();
        emp.setFirstName("garish");
        emp.setLastName("tumkur");
        emp.setEmail("garish.kr@cyclotis.net");
    }
    log.info("###### {}",agemp);
    Officess off1 = new Officess();
    Officess off2 = new Officess();
    Officess off3 = new Officess();
    off1.setOfficeName("Google");
    off2.setOfficeName("facebook");
    off3.setOfficeName("Instagram");
    Set<Officess> offices = emp.getOfficess();
    offices.add(off1);
    offices.add(off2);
    offices.add(off3);
    
    agentEmployeeRepository.save(emp);
    log.info("######## {}", offices);
    return "saved";   
}

I don't think any problem with code, but I think I have a problem while saving the data. Kindly any body refer the correct way to analyse this problem.

Looks like your mapping is not correct. Also verify you have a EMPID column. You don't need to use the @JoinTable annotation in your case.

As you are saving data you should use @PostMapping

StatusReport - removed private BigInteger EMPID; as it is used in joining

@Entity
@Table(name="statusreport")
public class StatusReport {
    private BigInteger COMPLIANCEID;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private BigInteger STATUSRPTID;
    private String COMMENTS;
    private Date CREATEDDATE;
    private BigInteger DEPARTMENT_ID;

    @OneToOne
    @JoinColumn(name = "EMPID")
    private Employees employee;
    
    //others methods
}
    

Employee - removed private BigInteger DEPARTMENT_ID; as it is used in joining

@Entity
public class Employees {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private BigInteger EMPID;
    private String FIRSTNAME;
    private String LASTNAME;
    private Date DOB;
    private String EMAIL;

    @OneToOne
    @JoinColumn(name = "DEPARTMENT_ID")
    private Department department;
    
    //others methods
}

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