ravikumar
ravikumar

Reputation: 101

What is the role of mappedBy in JPA or inverse="true" in Hibernate?

I have referred to various docs on Hibernate and have finally come to a very simple answer on this question.

I just wanted to clarify whether my final simple answer on this question is correct or not. Please help

Here is my answer

Inverse is a an attribute of tag in hibernate. It is generally used in OneToMany / ManyToOne bidirectional mapping.

inverse="true" means the child entity is the owner of relationship between the two entities and the child entity should take care of persistence operation with the foreign key column in the child table.

Upvotes: 2

Views: 4054

Answers (2)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 154190

You are right with your answer.

The reason for "inverse" is that in a database there is always one side controlling a relation (e.g. the FK side), while in your bidirectional domain model mapping you can make changes to both the one-to-many side (add/remove children) and the child side (setting the parent). That's why both sides need to stay in sync.

Hibernate can't automatically enforce the synchronism constraint, so it's the developer responsibility to make it happen. The only thing Hibernate can do is to observe one side only (in order to translate state transitions into SQL queries).

Therefore it's a good habit to provide add/removeChild like utility methods:

@Entity
public class Parent {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "parent", orphanRemoval = true)
    private List<Child> children = new ArrayList<Child>();

    public List<Child> getChildren() {
        return children;
    }

    public void addChild(Child child) {
        children.add(child);
        child.setParent(this);
    }

    public void removeChild(Child child) {
        children.remove(child);
        child.setParent(null);
    }
}

Upvotes: 2

Shailendra
Shailendra

Reputation: 9102

Adding to what @Vlad rightly pointed out, another side effect of how this impacts the DML query (atleast how Hibernate does it ) generated is that the DML for state change of non-inverse side is a single query (the update of foreign key is part of that DML) instead of two. This is well illustrated here.

Upvotes: 0

Related Questions