How to retrive objects from one to many using HQL

2019-09-14 23:18发布

问题:

Started to learn hibernate with examples. I have written a class "Team" that has one to many relationship with (a Collection of) players.

I need to get all the teams

  1. where player name is "X" (X is not the primary key of the Player table)
  2. where player "Y" is in

I think I have to get this done by using Criteria API or the HQL. Can someone tell how I can achieve it.

回答1:

Thsi will work for OneToMany relationship, ie 1 Team can Have many Players, and every no Player will be mapped to more than 1 Team.

@Entity
public class Team implements Serializable {
private Set<Player>    players;
}


@Entity
public class Player implements Serializable {
private String playerName;
}

where player name is "X" (X is not the primary key of the Player table)

SELECT t from Team t inner join t.players tp WHERE t.id = :id AND   tp.playerName = :name