0

I have several classes in my application:

  1. Individual, mapped to the Individual table
  2. Company, mapped to the Company table
  3. Address, mapped to the Address table

I want to build on-to-may associations between Individual and Address, and also between Company and Address, since naturally both individuals and companies can have zero or more addresses. I also want to use the same columns in the Address table to represent this association in the DB - one column referring to the ID of the owner entity, another signifying its type. So in SQL I would do something like this to extract addresses of the individual with id 5:

select * from Address where ref_id = 5 and ref_type = 'Individual'

For those that wonder why I do it, my motivation is twofold:

  1. Consolidate tables/columns that use similar data.
  2. Use more generic schema to provide future expansion of the domain model without requiring DDLs.

So the question is: how do I define such association in Hibernate? I'm new in Hibernate and I couldn't find the way to do it after several hours of struggling.

Thanks.

Stas
  • 1,059
  • 2
  • 16
  • 26
  • 1
    See http://stackoverflow.com/questions/217831/how-to-use-hibernate-any-related-annotations – axtavt Jun 08 '12 at 18:39
  • Thanks, it's quite helpful. However if I understand correctly, this will allow me to fetch addresses with associated objects (either Individual or Company). What if I want to fetch Individual with associated addresses? – Stas Jun 08 '12 at 19:37

1 Answers1

0

using xml:

<set name="adresses" where="ref_type = 'Individual'">
  ...
</set>

AFAIK there is a hibernate annotation to specify the where clause on the collection property

Firo
  • 30,626
  • 4
  • 55
  • 94
  • This will work in SQL, however as soon as I configure the "addresses" collection on both Individual and Company classes, Hibernate creates two unique foreign keys in the Address table on the same column. This later prevents me from inserting references from the Addresses, as they are not unique by nature (only the type/id pair is unique). – Stas Jun 11 '12 at 08:40
  • are you sure hibernate will do this although sdpecifying the where clause? if yes the add foreignkey="none" – Firo Jun 11 '12 at 08:53