Java 如何在hibernate中填充相同pojo类型的两个子成员变量
我有一个具有复合主键的父表(Java 如何在hibernate中填充相同pojo类型的两个子成员变量,java,hibernate,orm,Java,Hibernate,Orm,我有一个具有复合主键的父表(idOne,idTwo): 和一个子表。子表键包括(idOne,idTwo,child\u type): POJO结构有点不同。父POJO有两个引用类型的变量Child。下面是ParentPOJO结构 Parent ------------ Child typeOneChild; Child typeTwoChild; 因此,在从DB检索数据并填充父pojo时,我还需要基于child\u type列值填充typeOneChild和typeTwoChildpojo。
idOne
,idTwo
):
和一个子表。子表键包括(idOne
,idTwo
,child\u type
):
POJO结构有点不同。父POJO有两个引用类型的变量Child
。下面是Parent
POJO结构
Parent
------------
Child typeOneChild;
Child typeTwoChild;
因此,在从DB检索数据并填充父pojo时,我还需要基于child\u type
列值填充typeOneChild
和typeTwoChild
pojo。如果child\u type
列值为typeOne
,则此行将用于填充typeOneChild
pojo,对于列值typeTwo
,它将填充typeTwoChild
因此,基本上,当我检索父详细信息时,它应该执行以下SQL:
Select * from parent table where idOne=1 and idTwo=11191;
Select * from child table where idOne=1 and idTwo=11191 and child_type= 'typeOne'
Select * from child table where idOne=1 and idTwo=11191 and child_type= 'typeTwo'
我知道在正常情况下,表和pojo结构不符合预期,但我们无法更改表和模型结构。因此,请告诉我如何在hibernate中实现这一点?您应该能够使用带有鉴别器列的单表继承策略来实现这一点,该列如下所示:
@Entity
@Inheritance
@DiscriminatorColumn(name="child_type")
@Table(name="CHILD")
public abstract class Child {
@OneToOne
//specify the join here
private Parent parent;
}
@Entity
@DiscriminatorValue("typeOne")
public class TypeOneChild extends Child {
}
@Entity
@DiscriminatorValue("typeTwo")
public class TypeTwoChild extends Child {
}
@Entity
@Table(name="PARENT")
public class Parent {
@OneToOne(mappedBy = "parent)
private TypeOneChild typeOneChild;
@OneToOne(mappedBy = "parent)
private TypeTwoChild typeTwoChild;
}
请参见以下映射文档:
Select * from parent table where idOne=1 and idTwo=11191;
Select * from child table where idOne=1 and idTwo=11191 and child_type= 'typeOne'
Select * from child table where idOne=1 and idTwo=11191 and child_type= 'typeTwo'
@Entity
@Inheritance
@DiscriminatorColumn(name="child_type")
@Table(name="CHILD")
public abstract class Child {
@OneToOne
//specify the join here
private Parent parent;
}
@Entity
@DiscriminatorValue("typeOne")
public class TypeOneChild extends Child {
}
@Entity
@DiscriminatorValue("typeTwo")
public class TypeTwoChild extends Child {
}
@Entity
@Table(name="PARENT")
public class Parent {
@OneToOne(mappedBy = "parent)
private TypeOneChild typeOneChild;
@OneToOne(mappedBy = "parent)
private TypeTwoChild typeTwoChild;
}