[英]Mapping subclass list in Java using hibernate annotations
I have a problem with mapping a list of subclasses: 我在映射子类列表时遇到问题:
Model situation - I have an abstract class: 模型情况 - 我有一个抽象类:
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name="shapeType",
discriminatorType=DiscriminatorType.STRING
)
public abstract class Shape{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
protected Long id;
@Column(name="owner_id")
private Long ownerId;
@ManyToOne
@JoinColumn(updatable=false, insertable=false, name="owner_id")
private Owner owner;
}
and its subclasses: 及其子类:
@Entity
@DiscriminatorValue(value="triangel")
public class Triangel extends Shape {
}
and: 和:
@Entity
@DiscriminatorValue(value="circle")
public class Circle extends Shape {
}
Then, I have a class Owner
, which has a list of subclasses: 然后,我有一个类
Owner
,它有一个子类列表:
@Entity
public class Owner {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "owner", targetEntity=Shape.class)
private List<Triangel> triangels;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "owner", targetEntity=Shape.class)
private List<Circle> circles;
}
When I loop over the triangel
list: 当我遍历
triangel
列表时:
for(Object triangel: owner.getTriangels()){ //Using Triangel as a type throws ClassCastException
logger.info(triangel.toString());
}
it iterates all shapes objects, not just triangel
objects. 它迭代所有形状的对象,而不仅仅是
triangel
对象。 It seems to me, that hibernate ignores DiscriminatorColumn
during the selection subclasses in that situation. 在我看来,在这种情况下,hibernate会在选择子类期间忽略
DiscriminatorColumn
。
Mind, that without specification targetEntity
as Shape.class
in @OneToMany
, my application did not even start and had some problem with mapping initialization. 记住,没有规范
targetEntity
作为Shape.class
中的@OneToMany
,我的应用程序甚至没有启动并且在映射初始化时遇到了一些问题。
Configuration from pom.xml: 从pom.xml配置:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
<scope>provided</scope>
</dependency>
How am I supposed to do correct mapping configuration of that design? 我该如何进行该设计的正确映射配置?
最近在Hibernate 5.2.7中修复了这个问题: https : //hibernate.atlassian.net/browse/HHH-11375
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.