Hibernate version: 3.2.3
Name and version of the database you are using: MySQL 4.1
I have these classes:
Code:
class FileBean {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
int id;
// other properties
}
class ActivityBean {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
int id;
@MannyToMany
@JoinTable(
name="entity_files",
joinColumns={@JoinColumn(name="entity_id")},
inverseJoinColumns={@JoinColumn(name="file_hash")}
)
Set<FileBean> files;
}
class CampaignBean {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
int id;
@MannyToMany
@JoinTable(
name="entity_files",
joinColumns={@JoinColumn(name="entity_id")},
inverseJoinColumns={@JoinColumn(name="file_hash")}
)
Set<FileBean> files;
}
So, I have Activity and Campaign that both have a collection of files. A File may be used by both entities. The association is mapped by one single join table - "entity_files"
But because I use integer ids there is no way of telling which of those entities (Event or Campaign) is actually using a particular File. One solution would be to use GUIDs but I'm not allowed to change the type of the primary keys. Another solution would be to use separate join tables Event and Campaign but again that would mean changing the legacy db.
What I want is a way of adding an extra field in the join table that would act as a discriminator. Suppose I add a field "entity_type". If the value of that field is 'EVENT' then the relation should be between Event and File. If 'CAMPAIGN' then Campaign <-> File.
The closest thing I found was to use something like: @WhereJoinTable(clause="entity_type='EVENT'"). This works when retrieving the entities from database. But the problem is on save/update. I haven't found a way to tell hibernate to insert also the "discriminator" value in the join table. Is there a way to accomplish this ? Or is there a better way to map such a relation?