It's not a secret anymore!*
The moose likes Object Relational Mapping and the fly likes Conditional mapping Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Conditional mapping" Watch "Conditional mapping" New topic
Author

Conditional mapping

Ronald Castillo
Ranch Hand

Joined: Apr 16, 2011
Posts: 47

Hi ranch,

I know the title isn't exactly very descriptive but there's no way to express my situation with few words.

The thing is I'm trying to map the following, I have a legacy database in which one of the tables has a column named "model" and also another one named "model_id".
This table can either have a "foreign key" (not actually a real constraint on the database) to one table or another depending on the model. Something like:

id | model | model_id | status | code
1 | Task | 1 | pending | 156164
2 | Anything | 9 | pending | 647987

When the model is "Anything", the model_id points to the primary key of the table "anythings" and when is "Task" it points to the "tasks" table primary key.

How can I define this in my mapping using JPA? How do I map that table to an object model?

If my explanation was too shallow or you guys need any more information, please let me know.

Thanks a lot in advance
James Sutherland
Ranch Hand

Joined: Oct 01, 2007
Posts: 553
JPA does not directly support this, but some JPA providers may.

The closest solution in JPA, would be if Task and Anything shared inheritance (could be TABLE_PER_CLASS), then you could have a OneToOne to the superlass.
Alternatively you could just map the fields as Basic and query for the reference instead of mapping it.

In EclipseLink you can use a @VariableOneToOne mapping for this type of relationship.

See,
http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_variableonetoone.htm#CHDDFDGF


TopLink : EclipseLink : Book:Java Persistence : Blog:Java Persistence Performance
Ronald Castillo
Ranch Hand

Joined: Apr 16, 2011
Posts: 47

Hi James,

After taking a look at your solution, I stumbled upon Hibernate's @Any annotation (available since 3.3.1 GA).
Since I'm already using Hibernate in my project I decided to go for this alternative instead of EclipseLink's @VariableOneToOne annotation.

Thanks a lot for the help. I'm marking the thread as resolved.
 
Consider Paul's rocket mass heater.
 
subject: Conditional mapping
 
Similar Threads
Primary Key question
how to know the last auto-increment number using JDBC
entity bean for a table with No Primary key : Please Help,,,, URGENT
Entity beans which map two tables with foreign key pointing to alternate key (not primary key)
embedded class question