I'm trying to use HashMap
in entity Player
and my HashMap
is a compound of Integer
and another entity (entity ResourceOnPlayerAccount
) that is in a One-To-Many relationship, so I can prevent duplicated entries but still can keep the newest entry. My code worked well with a HashSet
but that way I couldn't keep the newest entries.
I already searched for another post. Among these posts, I found this one
Another Repeated column in mapping for entity error
But in this post, the problem seems to be the repeated call of a column, but in my code, I can't find something like that. And also I couldn't find an example with a HashMap
.
I added the Player entity as followed:
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;
...
The commented lines are my previous implementation with HashSet
that had worked.
Following is the other entity class:
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;
...
I just want to make sure that a player does not have duplicate resources in his account and that existing amounts of resources can be updated.
@MapKeyColumn
is used in a Map<Basic, Basic>
situation.
In your case, it is Map<Basic, Entity>
. For this @MapKey
is used:
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.