I've written some spring boot entities that have one-to-one relations inside. For example:
Student
Entity
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, mappedBy = "student")
private StudentClub studenttClub;
StudentClub
Entity
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "student_id", insertable = false, updatable = false)
private Student student;
When I try to update some student club information (i.e. club_code) by using .save
of the Student
repository, it deletes then inserts the updated data.
Hibernate: delete from student_club where club_code=? and student_id=?
Hibernate: insert into student_club (club_code, student_id) values (?,?)
Can we make it done by only 1 statement for example like
Hibernate: update ...
CodePudding user response:
.saveOrUpdate() method you can use it
-Calls either save() or update() on the basis of identifier exists or not. e.g if identifier exists, update() will be called or else save() will be called.
CodePudding user response:
Move @JoinColumn on StudentClub entity
@Entity
@Table(name = "STUDENT")
public class StudentEntity {
@Id
@SequenceGenerator(name = "StudentGen", sequenceName = "STUDENT_SEQ", allocationSize = 1)
@GeneratedValue(generator = "StudentGen", strategy = GenerationType.SEQUENCE)
@Column(name = "ID", unique = true)
protected Long id;
@OneToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
@JoinColumn(name = "CLUB")
public StudentClubEntity club;
}
@Entity
@Table(name = "STUDENT_CLUB")
public class StudentClubEntity {
@Id
@SequenceGenerator(name = "StudentClubGen", sequenceName = "STUDENT_CLUB_SEQ", allocationSize = 1)
@GeneratedValue(generator = "StudentClubGen", strategy = GenerationType.SEQUENCE)
@Column(name = "ID", unique = true)
protected Long id;
@Column(name = "NAME")
public String name = "";
@OneToOne(fetch = FetchType.LAZY)
public StudentEntity student;
}
Try to test ...
@Test
public void test() {
System.out.println("test");
StudentEntity student = new StudentEntity();
StudentClubEntity club = new StudentClubEntity();
student.club = club;
System.out.println("*****************************");
student = studentRepository.saveAndFlush(student);
student.club.name = "NEW NAME";
student = studentRepository.saveAndFlush(student);
System.out.println("*****************************");
}
Result
*****************************
Hibernate: call next value for student_seq
Hibernate: call next value for student_club_seq
Hibernate: insert into student_club (name, student_id, id) values (?, ?, ?)
Hibernate: insert into student (club, id) values (?, ?)
Hibernate: update student_club set name=?, student_id=? where id=?
*****************************