我寫了一些內部有一對一關系的 spring boot 物體。例如:
Student 物體
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY, mappedBy = "student")
private StudentClub studenttClub;
StudentClub 物體
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "student_id", insertable = false, updatable = false)
private Student student;
當我嘗試更新一些學生社團資訊(即club_code)使用.save的的Student存盤庫,它洗掉然后插入更新的資料。
休眠:從 student_club 中洗掉 club_code=? 和 student_id=?
Hibernate:插入 student_club (club_code, student_id) 值 (?,?)
我們可以只用 1 條陳述句來完成,例如
休眠:更新...
uj5u.com熱心網友回復:
.saveOrUpdate() 方法你可以使用它
- 根據識別符號存在與否呼叫 save() 或 update() 。例如,如果識別符號存在,則將呼叫 update(),否則將呼叫 save()。
uj5u.com熱心網友回復:
在 StudentClub 物體上移動 @JoinColumn
@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;
}
嘗試測驗...
@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("*****************************");
}
結果
*****************************
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=?
*****************************
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/355788.html
上一篇:我可以在另一個模塊中使用WebMvcConfigurer的實體嗎?
下一篇:必須在呼叫save()之前手動分配此類的id:com.employeesService.EmployeesService.model.Employee
