【问题标题】:Loading of Properties from database in Hibernate?在 Hibernate 中从数据库加载属性?
【发布时间】:2016-03-11 20:46:07
【问题描述】:

我有三个类 hierarchy

  • ParentClass.java

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

    具有用于此 ChildClass1 的属性 + 它还使用父类的一些公共属性

  • ChildClass2 extends ParentClass

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

所有属性都可以在两列表格中使用

**Key               value**     Type
---------------------------------------
propertyKey1    propertyValue1   Child1
propertyKey2    propertyValue2   Child1
propertyKey3    propertyValue3   Child2
propertyKey4    propertyValue4   Child2
propertyKey5    propertyValue5   CommonPorperty
..              ..               ..
propertyKeyn    propertyValuen   ..

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

为愚蠢的问题道歉......

提前致谢

【问题讨论】:

  • 你说的是两种属性吗? hibernate-entity 的属性是具有特定名称的 java 字段,但看起来您的属性名称是表中的值....请重写。
  • 检查描述符...

标签: java hibernate


【解决方案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;
    }
}

【讨论】:

  • 谢谢@hsnkhrmn..但是没有名为“Child1_Value”的列。和 Child2_Value,那么我们如何使用它呢?这里我的问题是没有关于子类的特定列
  • 我使用的值只是举例,你需要根据你的数据模型来改变它。基本上,您将在父实体上放置公共列(并进行映射),类的特定列是特定表(Child1 或 Child2)
  • 是的,你是对的.... hsnkhrmn.. 但是在这里我没有 chidl1 或 child2 的任何特定列。只有 propertykye 特定于 child1 或 child2。
  • 我明白了,这些字段在 DB 上没有映射。它们只是您实体上的瞬态字段,对吗?如果是这样,您需要用@Transient 标记他们的吸气剂,以免混淆休眠。子类可能有也可能没有额外的列,这不是必需的。 Hibernate 只是通过 Discriminator 列来理解它(如果没有,你应该添加)
猜你喜欢
  • 1970-01-01
  • 2020-07-11
  • 2015-03-27
  • 2010-11-26
  • 1970-01-01
  • 2018-07-21
  • 2012-06-07
  • 1970-01-01
  • 2014-07-29
相关资源
最近更新 更多