关于Hibernate级联关系手记

Os与OsFeature为一对多关系(OneToMany)
Os:
private Long osId;
.
.
.
private Set<OsFeature> osFeatures = new HashSet<OsFeature>();

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="OsId", unique = true, nullable = false, insertable = true, updatable = true)
public Long getOsId()
{
return osId;
}
...
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "os")
public Set<OsFeature> getOsFeatures()
{
  return osFeatures;
}
...

OsFeature:
private Os os;
.
.
.
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "OsId", referencedColumnName = "OsId", unique = false, nullable = false, insertable = true, updatable = true)
public Os getOs()
{
  return os;
}
...

注意:OsFeature里面的referencedColumnName,它表示多对一中一方的主键
如果不加该属性,在程序中,如果是保存一方Os的话,保存成功,但是在Os对应的表中会保存多次,即:os中关联多少个osFeature,os就会保存多少次,加上referencedColumnName属性后,一切正常

你可能感兴趣的:(Hibernate,OS)