简体   繁体   中英

Inner join using Hibernate?

I have a User:

@Entity
@Table(name = UserEntity.TABLE_NAME)
public class UserEntity {
  ...
  private List<TeamEntity> teams = new ArrayList<TeamEntity>();
  ...
  @ManyToMany(mappedBy="users" , fetch = FetchType.LAZY)
  public List<TeamEntity> getTeams() {
    return teams;
  }
}

and a Team:

@Entity
@Table(name = TeamEntity.TABLE_NAME)
public class TeamEntity {
   ...
   private List<UserEntity> users = new ArrayList<UserEntity>();
   ...
   @ManyToMany (fetch = FetchType.LAZY)
  @JoinTable(name= TeamEntity.TEAM_USER_TABLE,joinColumns=@JoinColumn(name=TeamEntity.TEAM_ID, referencedColumnName="ID",
      insertable = true, updatable = false, nullable = false),
      inverseJoinColumns=@JoinColumn(name=TeamEntity.USER_ID, referencedColumnName="ID",
      insertable = true, updatable = false, nullable = false),
      uniqueConstraints = @UniqueConstraint(columnNames = {TeamEntity.TEAM_ID, TeamEntity.USER_ID}))
  public List<UserEntity> getUsers() {
    return users;
  }
}

If I have an id of the user, what is the HQL query to retrieve all the teams that a user is a member of?

Thanks!

If you are not doing a where on the inner join, I wouldn't bother using HQL...

Because you are using Lazy loading, you have to initialize the teams collection... if you were using Eager fetching, you would not need the second line.

UserEntity user = (UserEntity) session.byId(UserEntity.class).load(id);
Hibernate.initialize(user.getTeams());

One way to query those is following JQPL (HQL being more or less superset of JPQL):

SELECT t 
FROM UserEntity u 
JOIN u.teams t 
WHERE u.id = :userId

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