ashes999 ashes999 - 2 months ago 10
Java Question

Mapping Multiple Classes to a Table in Hibernate, Without a DTYPE Column

I have two hibernate classes: a base class, and an extended class that has additional fields. (These fields are mapped by other tables.)

For example, I have:

@Entity
@Table(name="Book")
public class A {
private String ID;
private String Name;
// ...
}

@Entity
@Table(name="Book")
public class B extends A {
public String node_ID;
// ...
}

public class Node {
public String ID; // maps to B.node_ID
// ...
}


How do I map this in Hibernate? The hibernate documentation states three types of inheritence configurations: one table per class, one table with a type column, and a join table -- none of which apply here.

The reason I need to do this is because class A is from generic framework that's reused over multiple projects, and class B (and Node) are extensions specific to one project -- they won't be used again. In the future, I may have perhaps a class C with a house_ID or some other field.

Edit: If I try the above pseudo-code configuration (two entities mapped to the same table) I get an error that the DTYPE column doesn't exist. The HQL has a "where DTYPE="A" appended.

Answer

This is possible by mapping the @DiscriminatorColumn and @DiscriminatorValue to the same values for both classes; this can be from any column you use that has the same data regardless of which type (not sure if it works with null values).

The classes should look like so:

@Entity
@Table(name="Book")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="published")
@DiscriminatorValue(value="true")
public class A {
    private String ID;
    private String Name;
    // ...
}

@Entity
@Table(name="Book")
@DiscriminatorValue(value="true")
public class B extends A {
    public String node_ID;
    // ...
}