I think I have made something similar and I solved by introducing an intermediate entity. In your case it would be called something like AttachementSet. The solution introduces an extra column in the tables of those objects that you want to add attachments to. Here are some example mappings which may help you. There may be some error and you need to add options for cascading, lazy loading, etc.
For any entity that needs association to attachments:
Code:
<many-to-one
name="attachments"
column="attachmentset_id"
class="AttachmentSet"
... and other options as desired
/>
In AttachmentSet.hbm.xml:
Code:
<class
name="AttachmentSet"
table="ATTACHMENT_SETS"
... and other options as desired
>
<id column="attachmentset_id" />
<set
name="attachments"
inverse="true"
table="ATTACHMENT_JOINS"
... and other options as desired
>
<key column="attachmentset_id" />
<many-to-many class="Attachment" column="attachment_id" />
</set>
</class>
This should create one table (ATTACHMENT_SETS) with just a single column (attachmentset_id) and one join table (ATTACHMENT_JOINS) with two columns (attachmentset_id and attachment_id).
Another possible solution may be to use the <many-to-any> mapping but this probably needs to be done from the Attachment side. I am not very familiar with this so the examples below are just guesses. As I understand it though you get an extra column in the join table that holds the entity name. Eg something like:
Code:
<set
name="entities"
table="ATTACHMENT_JOINS"
... and other options
>
<key column="attachment_id"
<many-to-any
id-type="int"
meta-type="string"
>
<column
name="ENTITY_NAME"
length="255"
not-null="true"
/>
<column
name="ENTITY_ID"
not-null="true"
/>
</many-to-any>
</set>
The inverse mapping may need a "where" to filter on the ENTITY_NAME column, but I don't know if something like this works or not.
Code:
<set name="attachments"
cascade="all, delete-orphan"
lazy="true"
where="ENTITY_NAME='BR'"
inverse="true"
table="ATTACHMENT_JOINS">
<key column="ENTITY_ID" />
<many-to-many class="com.foo.bar.vo.Attachment"
column="ATTACHMENT_ID" not-found="ignore"/>
</set>