我正在尝试在实体 Player
中使用 HashMap
,而我的 HashMap
是 Integer
和另一个处于一对多关系的实体(实体ResourceOnPlayerAccount
),因此我可以防止重复的条目,但仍然可以保留最新的条目。我的代码与 HashSet
配合得很好,但这样我就无法保留最新的条目。
我已经搜索了另一篇文章。在这些帖子中,我找到了这个
Another Repeated column in mapping for entity error
但在这篇文章中,问题似乎是列的重复调用,但在我的代码中,我找不到类似的东西。而且我也找不到带有 HashMap
的示例。
我添加了 Player 实体,如下所示:
Player.java
@Entity
@Table(name="player")
public class Player {
// define fields
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="user_name")
private String userName;
@Column(name="password")
private String password;
@Column(name="display_name")
private String displayName;
@Column(name="email")
private String email;
// define relationships
// @OneToMany(cascade = CascadeType.ALL)
// @JoinColumn(name = "player_id")
// private Set<ResourceOnPlayerAccount> resourceOnPlayerAccountSet;
@OneToMany
@MapKeyColumn(name = "player_id")
private Map<Integer, ResourceOnPlayerAccount> resourceOnPlayerAccountMap;
...
注释行是我之前使用 HashSet
实现的,该实现已经有效。
下面是另一个实体类:
ResourceOnPlayerAccount.java
@Entity
@Table(name = "resources_on_player_account")
public class ResourceOnPlayerAccount {
// define fields
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "amount")
private double amount;
@Column(name = "resource_id")
private int resourceId;
...
我只是想确保玩家的帐户中没有重复的资源,并且可以更新现有的资源量。
最佳答案
@MapKeyColumn
用于Map<Basic, Basic>
情况。
就您而言,它是 Map<Basic, Entity>
。为此@MapKey
使用:
Specifies the map key for associations of type java.util.Map when the map key is itself the primary key or a persistent field or property of the entity that is the value of the map.
关于java - 又是: How to solve 'Repeated column in mapping for collection' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57371871/