• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Entity Beans and Composite-keys

 
JeanLouis Marechaux
Ranch Hand
Posts: 906
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
With Antity beans, I have (not really, but I prefer) to declare a primary Key class, lets say CustomerPK.
It's quite simple if my primary key is only 1 value, let's say custID.
But if it is a composite key, what do you think about it.
I can still declare all the field needed to compose the key, but I wonder if I will have other problems (maybe with hashcode and equals methods, or performance probel etc..)

If you guys already made an intensive use of composite keys with CMP, please share your experience.
TIA
 
Kyle Brown
author
Ranch Hand
Posts: 3892
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Composite keys are fine if that's the natural primary key of the table. This happens fairly often in bottom-up or meet-in-the-middle mappings.
And yes, you have to make your equals method check both keys, but that's generally not hard. Likewise, combine the hash of the two parts of your key to make up the hashCode. There shouldn't be any problems.
Kyle
 
Tim Holloway
Saloon Keeper
Pie
Posts: 18102
51
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sometimes you have no choice. A project I worked on last year had over half the datbase tables being referenced with no single column that would define a row as unique.
There are 3 methods in the Primary Key class that deserve attention when using multi-part keys:
1. The hashCode() method. You CAN be sloppy with this, but ideally you'll be tuning hashCode() to minimize collisions and that's true no matter how many parts make up the key.
2. The equals() method. If you don't compare on ALL fields in the key, you won't REALLY know if the comparand is or is not referring to the same EJB as the comparator.
3. The toString() method. Some EJB containers (and/or your debugging logic) like you to implement this method. It's useful if when displays something that helps you pin down which DBMS row you're looking at. I generally just "toString()" each key subcomponent and glue them together with slashes, dashes, or something else that makes it obvious what each component's individual value is.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic