在Hibernate 指南和此博客中,父物體(關系的反面)具有用于同步物體關系兩端的輔助方法。
父物體的休眠指南:
@Entity(name = "Person")
public static class Person {
@Id
@GeneratedValue
private Long id;
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Phone> phones = new ArrayList<>();
//Getters and setters are omitted for brevity
public void addPhone(Phone phone) {
phones.add( phone );
phone.setPerson( this );
}
public void removePhone(Phone phone) {
phones.remove( phone );
phone.setPerson( null );
}
}
子物體的休眠指南:
@Entity(name = "Phone")
public static class Phone {
@Id
@GeneratedValue
private Long id;
@NaturalId
@Column(name = "`number`", unique = true)
private String number;
@ManyToOne
private Person person;
//Getters and setters are omitted for brevity
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Phone phone = (Phone) o;
return Objects.equals( number, phone.number );
}
@Override
public int hashCode() {
return Objects.hash( number );
}
}
為什么我們不需要子物體中的輔助方法來確保兩個物體同步,如下所示?
@Entity(name = "Phone")
public static class Phone {
@Id
@GeneratedValue
private Long id;
@NaturalId
@Column(name = "`number`", unique = true)
private String number;
@ManyToOne
private Person person;
//Getters and setters are omitted for brevity
public void addPerson(Person person) {
setPerson( person );
person.getPhones().add( this );
}
public void removePerson(Person person) {
setPerson( null );
person.getPhones().remove( this );
}
}
uj5u.com熱心網友回復:
他們只是展示了這個概念。只要您可以確保它們的兩個關系都是配置屬性,從子物體同步關系是完全有效的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459048.html
標籤:休眠
