14 - Association Mapping in Hebernate

14.1 Overview

In earlier chapters we discussed persisting components using <composite-element tag where the component is persist as an value type whose life span is dependent on the parent object. We may have a collection of objects which are not value type instead are shared objects and in such case their life span cannot be dependent on the parent object. In such cases, the contained objects will have their own identifier and hence their own lifecycle.

In this chapter we will discuss following types of association mapping.

14.2 Many to One –

Think of the Cricket match and Stadium relationship where a multiple matches can be played at a single stadium. This is a Many to One association from Match to Stadium. In this scenario right now we are thinking from Match to stadium, which means we can navigate to stadium through match so this is a unidirectional association.

Hibernate does provide a <many-to-one> tag which can be used to map Many to One association.

From database design perspective, association is implemented by having a column in table representing “many” part of the relationship to hold the primary key of another table. This way this column is a foreign key.

In our example, Cricket_Match table will have an extra column to hold the stadium_ids

association-mapping.xml - <many-to-one> tag is used in Cricket Match mapping and its column attribute specifies the column name to hold the stadium ids. At the application end, we need not define an additional property corresponding to this column, hibernate does manage it internally.

Test Program – Below is the test program to insert and retrieve the data. In below program I have highlighted two statements and they are for saving Stadium and Cricket Match. Don’t you think that save call for stadium is unnecessary? Ideally it should be managed by Cricket save call only. To avoid unnecessary calls, there are cascade operations which we will discuss in upcoming chapters.