Home > front end >  Spring data JPA save and updating parent entity
Spring data JPA save and updating parent entity

Time:08-19

I have two entities called Student and Subject. They are stored in tables in the following format

student_id name grade
1 John 1
subject_id name
1 English
2 Math
subject_id student_id mark
1 1 75
2 1 75
**Student:**

@Table(name = "student")
@Data
public class Student {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "grade")
    private int grade;

    //getters and setters left out for this example
}

**Subject:**

@Table(name = "subject")
@Data
public class Subject {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    //getters and setters left out for this example
}

**StudentRepository:**

public interface StudentRepository extends JpaRepository<Student, Long> {
}


How do I make it so that everytime I add a student using a StudentController, the subjects are automatically added to the student.

CodePudding user response:

Create the third entity for the third table, create the student object and the subject object . put it in the third entity object, create the third repository and save that, all three tables will be updated together. Just make sure your relationships are correctly mentioned and you are done.

CodePudding user response:

Update your Student entity to encapsulate Subject. The idea is to explicitly define relationship between Student and Subject , and further leverag Cascade to propagate changes :

@Table(name = "student")
@Data
public class Student {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "grade")
    private int grade;

    @OneToOne(cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}, orphanRemoval = true)
    @JoinColumn(name = "SUBJECT_ID")
    Subject subject;
}

Note : You need to make sure that you populate Subject when storing Student.

For more clarity , explore the examples presented here : https://vladmihalcea.com/a-beginners-guide-to-jpa-and-hibernate-cascade-types/

  • Related