简体   繁体   中英

JPQL multiple joins and collections

I have players and game entities and I'm trying to get for each player all the games he has played and also how much right answer he has answered but the answers are stored in a third table named game_playeranswers (it's a collection ) so I have to select it and count the right answers. the game_playeranswers have three columns game_gameid, playeranswers and qid (question id).

I tried this to get the game playes by and the answers collection, it has returned 0 rows but X has played 1 game.

SELECT KEY(m), VALUE(m) FROM Game g JOIN g.playerAnswers m join g.player p where p.userName ='X'"

The Game entity is as follows

@Entity
@Table()
public class Game {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int gameID;

    @ElementCollection
    @CollectionTable(joinColumns = @JoinColumn())
    @MapKeyJoinColumn(name = "QID")
    @Column()
    public Map<TypePatternQuestions.Question, Boolean> playerAnswers = new LinkedHashMap<>();

    @ManyToMany
    private List<Category> choosenCategories = new ArrayList<>();

    @ManyToMany
    private List<Question> questions = new ArrayList<>();

    @Column()
    public Timestamp timestamp;

    @Column()
    public Timestamp gameStart;

    @Column()
    public Timestamp gameEnd;

    @Column()
    private int maxNumberOfQuestions;

    @ManyToOne()
    private Player player;

    //Getters and Setters

}

The Player is as follows

@Entity
@Table()
public class Player {

    public Player() {

    }

    @Id
    private String userName;

    @OneToMany(mappedBy = "player")
    private List<Game> games = new ArrayList<>();

    //Getters and Setters

}

I would say that the problems start not with a technical issue of creating the proper join (that may or may not be solved) but with a design flaw. It would be much better to keep the object model in this case closer to the relational model.

class Game

This class shall manage game details, not actual game played. This should include for example the game category but NOT a player or actual answers given.

class GameInstance

Or a similar name. This class is missing in your solution and is required to model the actual games played. Each Game may have multiple (ie zero or more) GameInstance s. This class should hold the player and other data related to actual game played.

class Player

Shall hold a List of GameInstance and NOT Game .


Taking this approach some of the many-to-many relations may become a one-to-many .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM