在Hibernate中从数据库加载属性?

时间:2015-12-07 09:34:40

标签: java hibernate

我有三个类 层次结构

  • private void moveToFirstGridToolStripMenuItem_Click(object sender, EventArgs e) { dataGridView2.Columns[currentColumnIndex].Visible = false; dataGridView1.Columns[currentColumnIndex].Visible = true; currentColumnIndex = -5; }

    ParentClass.java
  • having commons properties used for both ChildClass1 and ChildClass2.

    具有用于此ChildClass1 +的属性,它还使用父类中的一些常用属性

  • ChildClass1 extends ParentClass

    具有用于此ChildClass2 +的属性,它还使用父类中的一些常用属性

所有属性都可以在包含两列

的表中使用
ChildClass2 extends ParentClass

现在我不确定如何从hibernate继承加载它们?

为愚蠢的问题道歉...

提前致谢

1 个答案:

答案 0 :(得分:1)

你需要添加一个额外的列'Discriminator'来通知Hibernate当你在多个类型的同一个表上工作时应该加载哪个实例。 见例:

@Entity
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true)
@Table(name = "PARENT_TABLE")
@DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.INTEGER)
public abstract class ParentEntity implements java.io.Serializable {

    private long id;
    private String commonValue1;

    @Id      
    @Column(name = "ID", nullable = false)
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Column(name = "Common_Value1")
    public String getCommonValue1(){
        return commonValue1;
    }

    public void setCommonValue1(String commonValue1){
        this.commonValue1 = commonValue1;
    }
}


@Entity
@DiscriminatorValue("1")
public class ChildEntity1 extends ParentEntity {

    private String child1Value;

    @Column(name = "Child1_Value")
    public String getChild1Value(){
        return child1Value;
    }

    public void setChild1Value(String child1Value){
        this.child1Value = child1Value;
    }
}

@Entity
@DiscriminatorValue("2")
public class ChildEntity2 extends ParentEntity {

    private String child2Value;

    @Column(name = "Child2_Value")
    public String getChild2Value(){
        return child2Value;
    }

    public void setChild2Value(String child2Value){
        this.child2Value = child2Value;
    }
}