gpt4 book ai didi

java - 使用 JPA 时如何允许 arrayList 中出现重复项?

转载 作者:行者123 更新时间:2023-12-01 17:35:51 27 4
gpt4 key购买 nike

即使我将 @Id 设置为 true 并且在变量上使用一对多关系,我仍然收到“java.lang.IllegalStateException:同一实体的多个表示”。

以下是我试图将它们相互关联的类:

@Entity
@Table(name = "map_area")
public class MapArea extends BasicModel {
@Id
@Column(nullable = false, unique = true)
private String name;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "area", referencedColumnName = "name")
public List<AlternativeAreaName> alternativeNames;

public MapArea() {}

public MapArea(String name) {
this.name = name;
this.alternativeNames = new ArrayList<>();
}

}
@Entity
@Table(name = "alternative_area_name")
public class AlternativeAreaName implements Serializable {

@Id
@Column(nullable = false, unique = false)
private String area;

@Column(nullable = true)
private String alternativeName;

public AlternativeAreaName(){}

public AlternativeAreaName(String area, String alternativeName) {
this.area = area;
this.alternativeName = alternativeName;
}

}

我想让 JPA 根据名称变量创建另一个与此简单相关的表,但每当我尝试添加到列表并保存到数据库时,我都会得到

java.lang.IllegalStateException: Multiple representations of the same entity

MapArea mapArea = new MapArea("example");
AlternativeAreaName altAreaName1 = new AlternativeAreaName("example", "alt example");
AlternativeAreaName altAreaName2 = new AlternativeAreaName("example", "alt example2");
mapArea.alternativeNames.add(altAreaName2);

mapAreaRepository.save(mapArea);

最佳答案

您已使用私有(private)字符串区域字段作为实体AlternativeAreaName 的主键。所以当你尝试添加

AlternativeAreaName altAreaName1 = new AlternativeAreaName("example", "alt example");
AlternativeAreaName altAreaName2 = new AlternativeAreaName("example", "alt example2");

它们都有相同的主键。所以它抛出了上面的异常。

要生成 JPA 实体的主键,请检查

关于java - 使用 JPA 时如何允许 arrayList 中出现重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61043380/

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