Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hibernate

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.

like image 778
ashes999 Avatar asked Feb 01 '11 21:02

ashes999


1 Answers

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;
    // ...
}
like image 58
ashes999 Avatar answered Sep 27 '22 23:09

ashes999