10

I have an object with a field that can be a number of object types. This object is encoded in a single table with a discriminator column for the field's subtypes. Each of these subtypes have their fields mapped to a column in the parent objects table. I cannot seem to model this in hibernate. The code bellow will return null for getSubfield() regardless of what subtype data is in the table.

Schema

  id   type   whosit   whatsit  
+----+------+--------+---------+
| 1  | "A"  | "test" | null    |
| 2  | "B"  | null   | "test"  |
+----+------+--------+---------+

Domain Objects

@Entity
public class Parent {
    protected @Id @GeneratedValue int id;
    protected Subfield subfield;

    public Subfield getSubfield() {return subfield;} 
}


@Embeddable
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING)
public abstract class Subfield {}


@DiscriminatorValue("A")
public class TypeA extends Subfield {
    public String whosit;
}


@DiscriminatorValue("B")
public class TypeB extends Subfield {
    public String whatsit;
}

"SELECT p FROM parent p"

{id=1,subfield=null}
{id=2,subfield=null}

Is it possible to accomplish what I want with this object model, or do I need to get a bit more creative (this is a legacy database, changing the schema is not preferred)

1

3 Answers 3

7

As pointed by the asker, hibernate does not support inheritance of embeddable classes (https://hibernate.atlassian.net/browse/HHH-1910).

According to the Eclipse wiki, the JPA does not specify this behavior, but EclipseLink does support it (http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Entities/Embeddable#Inheritance).

My suggestion is to smash the class hierachy entirely inside Subfield. Horrible, but should work until this is solved.

Sign up to request clarification or add additional context in comments.

Comments

3

Ok you can't easily change the schema, but how about adding a couple of views?

2 Comments

Good idea, unfortunately, it is still a modification to the database structure. I am trying to solve this with code, if nothing else, it seems like something that hibernate could do and I am curious as to what I am doing wrong.
+1 to your comment and reminding SO that sometimes, we can't "make it right" and fix bad schema designs. :-)
1

I know this is old.

One way around this is as specified above. Create a view. You say you don't want to change the schema. Then don't. You can create a new schema which maps the old schema and does what you want. (Possibly depending on database)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.