仅包含复合主键中的一个字段的外键

仅包含复合主键中的一个字段的外键

本文介绍了JPA 2 - 仅包含复合主键中的一个字段的外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在JPA 2 / Hibernate中使用复合主键和外键。我正在尝试为国家和省份创建一个简单的场景:

I'm having trouble getting a composite primary key and foreign keys working in JPA 2/Hibernate. I'm trying to create a simple scenario with countries and provinces:

国家/地区实体:

@Entity
@Table(name = "country")
public class Country extends DomainObjectBase implements Serializable {

    @Id
    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @Basic(optional = false)
    @Column(name = "name")
    private String name;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "country")
    private List<Province> provinces;
}

省主键:

@Embeddable
public class ProvincePK implements Serializable {

    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @Basic(optional = false)
    @Column(name = "country_code")
    private String countryCode;
}

省实体:

@Entity
@Table(name = "province")
public class Province extends DomainObjectBase implements Serializable {

    @EmbeddedId
    protected ProvincePK provincePK;

    @Basic(optional = false)
    @Column(name = "name")
    private String name;

    @MapsId("country_code")
    @JoinColumn(name = "country_code", referencedColumnName = "code", insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private Country country;
}

这为我创建了正确的表格,但有一个例外:

This create the correct tables for me with one exception:

国家表:


  1. 代码PK

  2. name

省表


  1. 代码PK FK - 这就是问题是它创建国家表的代码列的外键引用

  2. country_code FK 这是我想要的唯一外键引用

  3. name

如何为hibernate映射我的实体/复合键生成我想要的架构?现在我不能将任何数据插入省,因为它期望该国家/地区包含省代码!

How do I map my entities/composite key for hibernate to generate the schema I want? Right now I can't insert any data into province because its expecting that country contains the province code!

感谢您的帮助。

推荐答案

试试这个。我发现当我处理这样的数据模型时,它对我有用。

Try this. I've found that it works for me when I work with data models like this.

@Entity
@Table(name = "province")
@IdClass(ProvincePK.class)
public class Province extends DomainObjectBase implements Serializable {

    @Id
    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @Id
    @Basic(optional = false, insertable = false, updatable = false)
    @Column(name = "country_code")
    private String countryCode;


    @Basic(optional = false)
    @Column(name = "name")
    private String name;

    @JoinColumn(name = "country_code", referencedColumnName = "code")
    @ManyToOne
    private Country country;

}

这篇关于JPA 2 - 仅包含复合主键中的一个字段的外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:48