在hibernate中映射具有主键和外键的三个表复合

时间:2014-12-02 00:25:26

标签: java hibernate jpa orm hibernate-mapping

我必须在hibernate中映射这些表,而且事实已经尝试了很多方面并且对我没有用,如果我可以帮助解决这个问题,我不会粘贴我拥有的代码,因为我认为它是不对,我改变了很多。

TABLE COUNTRY

idCountry(PK)

countryName

TABLE REGION

idRegion(PK)

idCountry(PK,FK)

RegionName

TABLE PROVINCES

idProvinces(PK)

idRegion(PK,FK)

ProvincesName

希望你能帮助我,非常感谢你

1 个答案:

答案 0 :(得分:1)

这是表映射:

@Entity
@Table(name = "COUNTRY")
public class Country implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "idCountry", unique = true, nullable = false)
    private int countryId;

    @Column(name = "countryName", nullable = false)
    private String countryName;

    @OneToMany(mappedBy = "regionPk.country", cascade = CascadeType.ALL)
    private Set<Region> regions = new HashSet<Region>(0);

    // Generate Getters, Setters, hashCode() and equals()

}

@Entity
@Table(name = "REGION")
public class Region implements Serializable {

    @EmbeddedId
    private RegionPk regionPk;  //  RegionPk contains the composite PK

    @Column(name = "RegionName", nullable = false)
    private String regionName;

    @OneToMany(mappedBy = "provincePk.region", cascade = CascadeType.ALL)
    private Set<Province> provinces = new HashSet<Province>(0);

    // Generate Getters, Setters, hashCode() and equals()

}

@Embeddable
public class RegionPk implements Serializable {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "idRegion", unique = true, nullable = false)
    private int regionId;

    @ManyToOne
    @JoinColumn(name = "idCountry", nullable = false)
    private Country country;

    // Generate Getters, Setters, hashCode() and equals()

}

@Entity
@Table(name = "PROVINCES")
public class Province implements Serializable {

    @EmbeddedId
    private ProvincePk provincePk;  //  ProvincePk contains the composite PK

    @Column(name = "ProvinceName", nullable = false)
    private String provinceName;

    // Generate Getters, Setters, hashCode() and equals()

}

@Embeddable
public class ProvincePk implements Serializable {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "idProvinces", unique = true, nullable = false)
    private int provinceId;

    @ManyToOne
    @JoinColumn(name = "idRegion", nullable = false)
    private Region region;

    // Generate Getters, Setters, hashCode() and equals()

}