使用Hibernate进行内连接?

时间:2014-01-21 17:55:45

标签: java hibernate hql

我有一个用户:

@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;
  }
}

和一个团队:

@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;
  }
}

如果我有用户的id,那么检索用户所属的所有团队的HQL查询是什么?

谢谢!

2 个答案:

答案 0 :(得分:0)

如果你没有在内连接上做什么,我就不会打扰使用HQL ......

因为您正在使用延迟加载,所以您必须初始化团队集合...如果您使用的是Eager抓取,则不需要第二行。

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

答案 1 :(得分:0)

查询这些内容的一种方法是遵循JQPL(HQL或多或少是JPQL的超集):

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