Hibernate:在“n:m”关系上映射“多对一”

时间:2012-01-31 12:32:20

标签: hibernate mapping

我有两个表,它们是1:n关系:

musician
{
id;
...
musician_status_id;
...
}

musician_status{
id;
name;
...
}

它们在Hibernate中映射:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "musician_status_id", nullable = false)
public MusicianStatus getMusicianStatus() {
   return this.musicianStatus;
}

现在我的数据库模型更改为n:m。

musician
{
id;
...
...
}

musician_has_status{
musician_id;
status_id;
organisation_id;
...
}

musician_status{
id;
name;
...
}

我有很多查询和代码在旧映射上进行中继。因此,我希望Hibernate getter只返回一个musician_status,具体取决于organisation_id。我的organisation_id存储在静态变量(登录数据)中。

我想到了一个视图和一个拦截器来检索某个organisation_id的musician_status。我真的不知道如何在Hibernate中实现这一点......

提前感谢。

添加了: 新的数据库映射看起来像这样:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "musician")
public Set<MusikerHasMusikerStat> getMusicianHasMusicianStatus() {
  return this.musikerHasMusicianStatus;
}

我想将其更改为:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "musician")
@Add a Filter or something like that?: where musician_has_status.organisation_id=LoginDat.getOrganisationID()
public MusicianStatus getMusicianStatus() {
  //or select the right status here?
  return this.musicianStatus;
}

2 个答案:

答案 0 :(得分:0)

将其映射到数据库中,并更改getMusicianStatus方法的代码:

@OneToMany(...)
@JoinColumn(...)
public void getStatusesWithOrganization() {
    return this.statusesWithOrganization();
}

/**
 * Returns the musician status for the organization stored in 
 * the static login data
 */ 
public public MusicianStatus getMusicianStatus() {
    for (StatusWithOrganization s : statusesWithOrganization) {
        if (LoginData.organizationId.equals(s.getOrganization().getId())) {
            return s.getMusicianStatus();
        }
    }
    return null;
}

答案 1 :(得分:0)

我建议您使用@Where( clause = "MYCONDITION" )子句,因为它会在查询级别过滤数据,从而为您提供更好的性能。