为什么Hibernate选择相同的列4次?帮助映射?

时间:2011-08-25 13:37:42

标签: hibernate jpa-2.0

我的课程看起来像这些。为什么同一列被选中4次?映射有什么问题?

@Entity @Table(name="CLIENTS")
public class Client implements Serializable {

  @Id @GeneratedValue   @Column(name="GENERATED_ID")
  private Long id;

  @Column(name="NAME")
  private String name;

  @OneToMany(cascade=CascadeType.ALL, mappedBy="client", fetch=FetchType.EAGER)
  private Map<ParamPK, Param> params = new HashMap<ParamPK, Param>();
}

@Entity @Table(name="PARAMS")
public class Param implements Serializable {

  @EmbeddedId
  private ParamPK paramPK;

  @Column(name="VALUE")
  private String value;

  @ManyToOne @MapsId("clientId")
  private Client client;
}

@Embeddable
public class ParamPK implements Serializable {

  @Column(name="PARAM_KEY")
  private String key;

  @Column(name="CLIENT_GENERATED_ID")
  private Long clientId;
}

select生成的查询将获得相同的列4次。

/* from Client */ 
select
    client0_.GENERATED_ID as GENERATED1_1_,
    client0_.NAME as NAME1_ 
from
    CLIENTS client0_

/* load one-to-many Client.params */ 
select
    params0_.client_GENERATED_ID as client3_1_1_,
    params0_.client_GENERATED_ID as client3_1_,
    params0_.PARAM_KEY as PARAM1_1_,
    params0_.CLIENT_GENERATED_ID as CLIENT3_1_,
    params0_.client_GENERATED_ID as client3_0_0_,
    params0_.PARAM_KEY as PARAM1_0_0_,
    params0_.VALUE as VALUE0_0_ 
from
    PARAMS params0_ 
where
    params0_.client_GENERATED_ID=?

注意使用Hibernate 3.5.3。其余的样板代码已被删除为无关紧要。

1 个答案:

答案 0 :(得分:3)

你忘了告诉Hibernate什么构成了参数图的关键。将以下注释添加到此地图:

@OneToMany(cascade=CascadeType.ALL, mappedBy="client", fetch=FetchType.EAGER)
@MapKey(name = "paramPK")
private Map<ParamPK, Param> params = new HashMap<ParamPK, Param>();

这告诉Hibernate Param实体的paramPK属性是地图的关键。