gpt4 book ai didi

java - 使用 hibernate 注解在 Java 中映射子类列表

转载 作者:行者123 更新时间:2023-12-02 08:40:35 24 4
gpt4 key购买 nike

我在映射子类列表时遇到问题:
模型情况 - 我有一个抽象类:

@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;
}

及其子类:

@Entity
@DiscriminatorValue(value="triangel")
public class Triangel extends Shape {
}

和:

@Entity
@DiscriminatorValue(value="circle")
public class Circle extends Shape {
}

然后,我有一个类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;
}

当我循环遍历triangel列表时:

for(Object triangel: owner.getTriangels()){ //Using Triangel as a type throws ClassCastException
logger.info(triangel.toString());
}

它迭代所有形状对象,而不仅仅是triangel对象。在我看来,在这种情况下,hibernate 在选择子类期间会忽略 DiscriminatorColumn

请注意,如果没有将 targetEntity 指定为 @OneToMany 中的 Shape.class,我的应用程序甚至无法启动,并且在映射方面存在一些问题初始化。

来自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>

我应该如何对该设计进行正确的映射配置?

最佳答案

这是最近在 Hibernate 5.2.7 中修复的问题:https://hibernate.atlassian.net/browse/HHH-11375

关于java - 使用 hibernate 注解在 Java 中映射子类列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32036228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com