Gambit2007
Gambit2007

Reputation: 3958

Hibernate - why should we map relationships?

I just started learning Hibernate recently and i was wondering: what is the point of using relationship mapping annotations such as @OneToMany or @OneToOne?

Do we have to do that? If not, why should we?

The only explanation i've seen anywhere online was:

Association mappings are one of the key features of JPA and Hibernate. They model the relationship between two database tables as attributes in your domain model. That allows you to easily navigate the associations in your domain model and JPQL or Criteria queries.

But i'm not too sure what the last sentence in that paragraph means.

Upvotes: 0

Views: 354

Answers (1)

Conrad
Conrad

Reputation: 564

Explanation you've provided is correct.

allows you to easily navigate the associations in your domain model and JPQL or Criteria queries.

Consider following example. There is no manual fetching of branches. You can easily access branches field and hibernate will generate sql to fetch them from DB.

Tree tree = entityManager.getReference(Tree.class, 1L);
tree.getBranches(); //hibernate will fetch this automatically

class Tree {
   @OneToMany(mappedBy="tree", fetch = FetchType.LAZY)
   List<Branch> branches;
}

class Branch {
   @ManyToOne(fetch = FetchType.LAZY)
   Tree tree;
}

Same goes to JPQL. You can easily add branches into query without specifying ON condition. Hibernate will automatically add it when translating JQPL to SQL.

select t.* from Tree t join t.branches;

Last thing, you don't always add these kind of mappings. There are some cases when there is connection between tables but it's not represented in data model.

Upvotes: 2

Related Questions