Hibernate Subselect with class inheritance

时间:2017-08-28 11:38:40

标签: java hibernate

我有两个具有相同字段的对象,但是来自不同的表(foo_something和bar_something实际上不是普通表,有几个连接操作的结果)。我使用@Subselect hibernate注释来获取数据。我可以制作这样的类结构,但哪种工作正常?此类结构不起作用,因为注释不会继承。如果我使用@Inheritance注释,则会收到错误Unknown column foo_somethingca0.DTYPE

class Something {

    @Id @Column Long id;
    @Column String name;
    @Column String description;

    //getters, setters, constructors

}

@Entity
@Immutable
@Subselect("SELECT id, name, description FROM foo_something")
class FooSomething extends Something {

}

@Entity
@Immutable
@Subselect("SELECT id, name, description FROM bar_something")
class BarSomething extends Something {

}

UPD。

谢谢@HenryMartens,我添加了注释@Entity@Inheritance以及TABLE_PER_CLASS策略,并将类抽象化,现在它正常工作:

@Entity
@Inheritance(strategy = TABLE_PER_CLASS)
abstract class Something {

    @Id @Column Long id;
    @Column String name;
    @Column String description;

    //getters, setters, constructors

}

@Entity
@Immutable
@Subselect("SELECT id, name, description FROM foo_something")
class FooSomething extends Something {

}

@Entity
@Immutable
@Subselect("SELECT id, name, description FROM bar_something")
class BarSomething extends Something {

}

1 个答案:

答案 0 :(得分:1)

Hibernate中的DTYPE是鉴别器列。它用于表示像示例一样持久存储在同一数据库表中的某些对象之间的区别。 您可以使用here注释添加一个鉴别器列。

在具体类上,您可以使用@DiscriminatorColumn为带注释的类设置discriminator列的值。

例如:

@Entity
@Inheritance( strategy = InheritanceType.TABLE_PER_CLASS ) 
@DiscriminatorColumn(name="DISC", discriminatorType=STRING, length=20)
class abstract Something {

    @Id 
    @Column 
    Long id;

    @Column 
    String name;

    @Column 
    String description;

    //getters, setters, constructors 
}

@Entity
@Table("FOO_SOMETHING")
@Immutable
@DiscriminatorValue("FooSomething")
class FooSomething extends Something {

}

@Entity
@Table("BAR_SOMETHING")
@Immutable
@DiscriminatorValue("BarSomething")
class BarSomething extends Something {

}