How do I create 2 separate instances on an inner class as separate properties of the outer class which is a JPA entity?

Viewed 35

I have a class called User, within this class they previously had the following properties:

@Entity(name = "User")
@Table(name = "user")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "username", unique = true)
    private String username;

    @Column(name = "password")
    private String password;
    
    private Integer victories;
    private Integer defeats;

    private Double victoryRatio;
}

However, I now need to draw a distinction between different game types, for example there will be competitive games and non-competitive games.

This means that every time a comp OR non-comp game is played the standard victories, defeats and victory ratio must be updated. But when a comp game is played I also need the new 'comp' variables to increase also as below:

@Entity(name = "User")
@Table(name = "user")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "username", unique = true)
    private String username;

    @Column(name = "password")
    private String password;
    
    private Integer victories;
    private Integer defeats;

    private Double victoryRatio;

    private Integer compVictories;
    private Integer compDefeats;        
    private Double compVictoryRatio;
}

This leads to a lot of code duplication within other classes such as service classes. I want to create a new class called UserStats as such:

public class UserStats {
   
    private Integer victories;
    private Integer defeats;
    
    private Double victoryRatio;

}

And then have within the original User entity:

private UserStats userStats;
private UserStats compUserStats;

But unfortunately this is not working and IDEA has highlighted the 'UserStats' in the above code in red.

Do I need to create the UserStats as a seperate entity and then do like:

@OneToMany
private UserStats userStats;

@OneToMany
private UserStats compUserStats;

I am unsure how to do this the best way, any help would be appreciated, thanks.

1 Answers

And then have within the original User entity:

private UserStats userStats;
private UserStats compUserStats;

That looks doable in Java. What is the IDE's error message? It most likely isn't able to map to a JPA entity. In your UserStats Class, did you correctly define this? Does your database have table a for this? https://www.baeldung.com/jpa-entities

Related