In one of my previous posts I made an overview of Hibernate and its main principles of work. Now I want to talk about one of the most important features of Hibernate – associations. An association represents a relationship between two tables in a database. So let’s go further because great things wait for us.

Every modern RDBMS supports relationships. There are four known types of relationships:

  • one to one
  • one to many
  • many to one
  • many to many

I will not stop giving in detail every type because they are out of the post theme. As mentioned above, Hibernate can programmatically provide a way of relations between DB tables in an application. I’m going to consider just annotation based approach of associations, XML approach will be omitted. So here are four appropriate annotations which help to obtain appropriate types of DB table relationships:

  • @OneToOne
  • @OneToMany
  • @ManyToOne
  • @ManyToMany

Everything seems to be very simple and trivial, but if we face the truth we will soon understand that, setting up correct association between two entities is one of the hardest things in Hibernate. There are a lot of reasons: plenty of settings which you can use within setting up, a lot of details which you need to keep in your mind while obtaining an association.

There is one strange thing happening to most of developers – associations can be of two types. Hibernate provides unidiractional and bidirectional associations. Don’t try to make a parallel with RDBMS, because they have relations and with their help you can access data from both sides of relation. Meanwhile in Hibernate you can setup association which will be unidirectional and will give an access to data just for one of entities (owner side). This is possible due to references between classes.

Also Hibernate supports primary key association and foreign key association. You can specify a behaviour of records in tables with the help of cascade attribute. So as you can see you have a wide range of possibilities while developing with Hibernate. In the following articles I’m going to provide some examples with MySQL and OneToOne mapping (unidirectional and bidirectional).

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog