How to save entities dependent on others with JPA (Java Persistence API)?

1

I am currently developing an api-rest with spring-boot, whose services will be called from an application in angular, the SQL server is being used as database manager. I have the following tables:

I am capturing the data of an insured, through a form in angular

The relationship I have between these two entities is one by one, an Insured is a person, so I have defined their classes:

INSURED

import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.sql.Time;
import java.util.Date;

@Entity
@Table(name = "Assureds")
@Access(AccessType.FIELD)
public class Assured extends ParentEntity {

    private static final long serialVersionUID = -5015666908034563954L;

    public Assured() {
        super();
    }

    @Column(name = "Assuredtype_Id", nullable = true) 
        private Integer assuredtypeId;    

    @Column(name = "Person_Id", nullable = false) 
    private int personId;

    @Column(name = "Applicantnumber", nullable = true) 
    private Integer applicantNumber;

    @Column(name = "Deceaseddate", nullable = true)
    private Date deceasedDate;

    @Column(name = "Deceasedlocality", nullable = true)
    private String deceasedLocality;

    @Column(name = "Since", nullable = true) 
    private Time since;

    @Column(name = "Until", nullable = true) 
    private Time until;

    /*Un asegurado es una persona */
    @OneToOne(cascade= {CascadeType.ALL})
    @JoinColumn(name="Person_Id", referencedColumnName="id", insertable = false, updatable = false)
    public Person person;



    public Integer getAssuredtypeId() {
        return assuredtypeId;
    }

    public void setAssuredtypeId(Integer assuredtypeId) {
        this.assuredtypeId = assuredtypeId;
    }

    public int getPersonId() {
        return personId;
    }

    public void setPersonId(int personId) {
        this.personId = personId;
    }

    public Integer getApplicantNumber() {
        return applicantNumber;
    }

    public void setApplicantNumber(Integer applicantNumber) {
        this.applicantNumber = applicantNumber;
    }

    public Time getSince() {
        return since;
    }

    public void setSince(Time since) {
        this.since = since;
    }

    public Time getUntil() {
        return until;
    }

    public void setUntil(Time until) {
        this.until = until;
    }

    public AssuredType getAssuredtype() {
        return assuredtype;
    }

    public void setAssuredtype(AssuredType assuredtype) {
        this.assuredtype = assuredtype;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

    public Date getDeceasedDate() {
        return deceasedDate;
    }

    public void setDeceasedDate(Date deceasedDate) {
        this.deceasedDate = deceasedDate;
    }

    public String getDeceasedLocality() {
        return deceasedLocality;
    }

    public void setDeceasedLocality(String deceasedLocality) {
        this.deceasedLocality = deceasedLocality;
    }

}

PERSON

import java.util.Date;
import java.util.List;
import javax.persistence.*;

@Entity
@Table(name = "Persons")
@Access(AccessType.FIELD)

public class Person extends ParentEntity {

    private static final long serialVersionUID = -5015666908034563954L;

    public Person() {
        super();
    }


    @Column(name = "Name", nullable = false) 
    private String name;    

    @Column(name = "Lastname", nullable = false) 
    private String lastName;    

    @Column(name = "Picture_Id", nullable = true) 
    private Integer pictureId;

    @Column(name = "Dni", nullable = false, length = 255)
    private String dni;  

    @Column(name = "Email", nullable = false, length = 255) 
    private String email;

    @Column(name = "Nationality", nullable = true, length = 255) 
    private String nationality;

    @Column(name = "Birthdate", nullable = true, length = 255) 
    private Date birthDate;

    @OneToOne(mappedBy="person")
    private Set<Assured> assured;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getPictureId() {
        return pictureId;
    }

    public void setPictureId(Integer pictureId) {
        this.pictureId = pictureId;
    }

    public FileUpload getFileUpload() {
        return fileUpload;
    }

    public void setFileUpload(FileUpload fileUpload) {
        this.fileUpload = fileUpload;
    }

    public String getDni() {
        return dni;
    }

    public void setDni(String dni) {
        this.dni = dni;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    public List<Phone> getPhones() {
        return Phones;
    }

    public void setPhones(List<Phone> phones) {
        Phones = phones;
    }

    public List<Address> getAddresses() {
        return this.Addresses;
    }

    public void setAddresses(List<Address> addresses) {
        this.Addresses = addresses;
    }

    public void setAddress(Address address) {
        Addresses.add(address);
    }
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNationality() {
        return nationality;
    }

    public void setNationality(String nationality) {
        this.nationality = nationality;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }


}

PARENTENTITY

import java.io.Serializable;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.GenerationType;

@MappedSuperclass
@Access(AccessType.FIELD)
public class ParentEntity implements Serializable{


    private static final long serialVersionUID = -2890482081142183458L;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id", unique = true, nullable = false)

    private Integer id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

}

And this is my controller where I define the urls

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class AssuredController {
    @Autowired
    protected AssuredService assuredService;
    protected ObjectMapper mapper;

     @CrossOrigin(origins = "*")
    @RequestMapping(value = "/api/assured/saveOrUpdate",method = RequestMethod.POST)
    public RestResponse saveOrUpdate(@RequestBody String assuredJSON) throws JsonParseException, JsonMappingException, IOException {
        this.mapper= new ObjectMapper();
        Assured assured= this.mapper.readValue(assuredJSON,Assured.class);
        this.assuredService.save(assured);
        return new RestResponse(HttpStatus.OK.value(), "Operacion Exitosa");
    }
    @RequestMapping(value = "/api/assured/getAll", method = RequestMethod.GET)
    public List<Assured> getAll() {
        return this.assuredService.findAll();
    }
    @RequestMapping(value = "/api/assured/delete", method = RequestMethod.POST)
    public void deleteUser(@RequestBody String assuredJson) throws Exception {
        this.mapper = new ObjectMapper();

        Assured assured = this.mapper.readValue(assuredJson, Assured.class);

        if (assured.getId()==0) {
            throw new Exception("El id esta nulo");
        }
        this.assuredService.delete(assured.getId());
    }
}

REPOSITORY

package dao;

import org.springframework.data.jpa.repository.JpaRepository;
import com.sotec.BestLegalAssistance.model.Assured;

public interface AssuredRepository extends JpaRepository<Assured, Integer>{
    @SuppressWarnings("unchecked")
    Assured save(Assured assured);
    void delete(int id);
}

** The api saves, removes and edits perfectly when I send the entities separately, that is, I capture the data of the person, I save it, I create a method to bring the saved person, I take out his id and proceed to save the insured with the id of the person I brought. I've been studying spring for 1 month as such, I'm a novice.

What I want to do is send you from the front-end the insured data with your personal object, and believe me the two entities in a single request, knowing that an insured has a foreign key of the person Id. When I try to insert the insured I get an error in the java console saying that the person_id can not be null, so I see, the person does not believe me and when he tries to save the insured does not find the Person_ID.

I do not know if you can do what I ask, I have documented with respect to the subject but I do not get an example to help implement it **

    
asked by Virgilio La Rosa 31.01.2018 в 21:46
source

1 answer

0

In your Assured parent object you must occupy the annotation

@OneToOne(cascade = CascadeType.ALL)

In this way, hibernate knows that if it receives the object with its child, which in this case is Person, both objects must persist.

An example that although it is in English is useful is in this link

    
answered by 31.01.2018 / 21:57
source