0

My entity class MemberDispatch has 2 natural keys: Members and Dispatch. Both Members and Dispatch are entity classes themselves.

Right now, the key of MemberDispatch is ID-- a surrogate key. Members and Dispatch are composed in MemberDispatch as entity fields and are not part of the key.

Whenever I need to save-and-not-update, i.e., save only if a corresponding (Members, Dispatch) doesn't exist in MemberDispatch, I first am fetching from MemberDispatch (if exists) the record matching the (Members, Dispatch) pair, and saving ony if that query returns null.

If I'd instead define and use the natural keys (Members and Dispatch) as the key, i'd save directly without checking first a record already exists. With this, I'd have achieved what I'm looking for-- Hibernate would make sure of the uniqueness of (Members and Dispatch) pair in the database table.

I've seen Why are composite keys discouraged in hibernate? and some other arguments against composite keys in Hibernate.

My Q is: is there a better way of designing the entity classes without getting into composite keys?

//-------------------------

EDIT:

I achieved since by overriding equals() of MemberDispatch on fields Members and Dispatch. it's throwing a org.hibernate.exception.ConstraintViolationException when I attempt to save an existing (Members, Dispatch) pair.

The Q then would be - why would I need JPA uniqueness constraints (thanks JBNizet and Nathan Hughes) while I have this?

Community
  • 1
  • 1
Roam
  • 4,831
  • 9
  • 43
  • 72
  • 1
    You don't need (member, dispatch) to be a composite primary key to be able to do that. All you need is a unique constraint on (member, dispatch). – JB Nizet Mar 21 '16 at 20:03
  • @JBNizet how is it done - whats the annotation for that? so, i'd be defining a constraint for 2 fields – Roam Mar 21 '16 at 20:06
  • related: [How to introduce multi-column constraint with JPA annotations?](http://stackoverflow.com/q/2772470/217324) – Nathan Hughes Mar 21 '16 at 20:08
  • Yes. I don't define my schema with annotations, but with SQL. But it's possible to use an annotation to do it: http://docs.oracle.com/javaee/6/api/javax/persistence/UniqueConstraint.html – JB Nizet Mar 21 '16 at 20:09
  • @JBNizet , NathanHughes I think I worked this around -- see my edit in the Q. how would this be any better/worse than what you suggested? – Roam Mar 21 '16 at 20:26
  • I don't see how that could work. If you haven't loaded any entity yet, and just try to insert a new entity with a member/dispatch pair that already exists in the DB, the database won't reject the insert based on your equals() method. – JB Nizet Mar 21 '16 at 20:29

0 Answers0