Home > database >  Why helper method for synchronizing both ends of the entity relationship locates in parent entity?
Why helper method for synchronizing both ends of the entity relationship locates in parent entity?

Time:04-18

In Hibernate guide and this blog, it is the parent entity (inverse side of the relationship) that has helper method for synchronizing both ends of the entity relationship.

Hibernate guide for parent entity:

@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 );
    }
}

Hibernate guide for child entity:

@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 );
    }
}

Why we don't need helper methods in child entity to make sure both entities are synchronized like the following?

@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 );
    }
}

CodePudding user response:

They just demonstrate the concept. It is perfectly valid to synchronise the relationship from the children entity as long as you can make sure that both of their relationship are configured property.

  • Related