简体   繁体   English

使用Hibernate进行内部联接?

[英]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? 如果我有该用户的ID,该HQL查询将检索该用户所属的所有团队吗?

Thanks! 谢谢!

If you are not doing a where on the inner join, I wouldn't bother using HQL... 如果您不在内部联接上执行任何操作,那么我就不会使用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. 因为使用的是延迟加载,所以必须初始化teams集合...如果使用的是Eager访存,则不需要第二行。

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): 一种查询方法是遵循JQPL(HQL或多或少是JPQL的超集):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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