Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Conditional mapping

 
Ronald Castillo
Ranch Hand
Posts: 47
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 553
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ronald Castillo
Ranch Hand
Posts: 47
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic