On 12/06/12 7:01pm, Schönfisch, Jörg wrote:
Hi,
I have two tables, one relates to an object entity, the other is a join table. A FK
relationship exists between those two. However the "other" IDs in the join
table may be present in several different tables so I cannot define a FK relationship for
them. Thus I directly want to read a list of IDs and not convert them into object
entities. The mapping of IDs to objects will later take place in the business code.
Any hints on how to do this or if it's possible at all?
What you are describing is a polymorphic join. In Rails it looks like this:
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
There is no built-in construction in Cayenne, but it isn't hard to map. Let's pretend you
want to have the ability to add "attachments" to various other entities.
Contacts, Artists, Paintings. These attachments might be a picture or other information.
So you create:
[Attachment]
id
other columns
[AttachmentRelation]
foreignRecordId (int)
foreignTable (string or enum)
[ContactAttachmentRelation]
[PaintingAttachmentRelation]
[ArtistAttachmentRelation]
These last three classes you create in Cayenne model and you make them a
subclass of AttachmentRelation. There is no database table that goes with them,
so effectively you are creating them as single table inheritance. Three
subclasses, and only table table in the database.
Put a method like this in the AttachmentRelation:
public abstract void setAttachedRelation(Attachable attachable);
And then code like this goes in the ContactAttachmentRelation subclass:
public void setAttachedRelation(Attachable attachable) {
setAttachedContact((Contact) attachable);
}
The model will have a qualifier like this:
<obj-entity name="ContactAttachmentRelation" superEntityName="AttachmentRelation"
className="x.y.z.ContactAttachmentRelation" clientClassName="x.y.z.ContactAttachmentRelation">
<qualifier><![CDATA[entityIdentifier like "Contact"]]></qualifier>
</obj-entity>
There is a bit more to do, but it is pretty simple. The main trick is to use
the Cayenne inheritance and let it handle all your SQL generation. It works
really nicely and we've had something like this in production for many years.
Ari
--
-------------------------->
Aristedes Maniatis
GPG fingerprint CBFB 84B4 738D 4E87 5E5C 5EFA EF6A 7D2E 3E49 102A