This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Object Relational Mapping and the fly likes Help Needed.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Help Needed...." Watch "Help Needed...." New topic

Help Needed....

shri mon
Ranch Hand

Joined: Jan 11, 2005
Posts: 63
I have a table where a combination of two columns is a primary key.
How should i specify that in the mapping file?

Thanks in advance.

Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

Ideally, if you can change the data model, give this table a surrogate key. Its far easier in the long run.

If you can't, you need to map the composite key. To do this Hibernate defines a composite-id element you use instead of the normal id element in your mapping files. You could map the key like this:

In order for Hibernate to properly manage object identity with a composite key, you need to override the equals() and hashCode() methods in your POJO class. This way your POJO itself is its own key.

The alternative, and more elegant, way is to define a seperate identifier class which contains the two properties in your key and overrides equals() and hashCode(). If you did this, your mapping looks like this:

[ April 22, 2005: Message edited by: Paul Sturrock ]

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
shri mon
Ranch Hand

Joined: Jan 11, 2005
Posts: 63
Thanks a lot....
I agree. Here's the link:
subject: Help Needed....