如何使用JPA / Hibernate注释持久化地图

时间:2015-11-18 12:44:27

标签: hibernate jpa collections annotations mapping

Table Structure

我在使用JPA 1.0 Annotations持续保持上述关系时遇到了问题。

我可以使用以下完美运行的XML来映射它:

<class name="Exposure" table="Exposures">
    <id name="id" column="Id"/>
    <property name="name" column="name" not-null="true"/>

    <set name="rules" table="ExposureRules" lazy="true" cascade="all, delete-orphan">
        <key column="TypeId"/>
        <one-to-many class="ExposureRule"/>
    </set>
</class>

<class name="ExposureRule" table="ExposureRules">
    <id name="id" column="Id"/>
    <property name="inclusive" column="Inclusive" not-null="true"/>

    <map name="attributes" table="ExposureRuleAttributes" lazy="true" cascade="all">
        <key column="RuleId"/>
        <index column="Attribute" type="string"/>
        <element column="Value" type="string"/>
    </map>
</class>

当我尝试使用Annotations持久化时,我收到以下错误:

Foreign key (FKA635AE7A4160E727:ExposureRuleAttributes [RuleId])) must have same number of 
columns as the referenced primary key (ExposureRules [TypeId,rules_id])

我认为问题在于我如何在 ExposureRules 类中注释属性地图,但我无法找出正确的方法做到了吗?

曝光等级:

@Entity
@Table(name="Exposures")
public class Exposure {

    @Id
    private int id;

    @Column(nullable=false)
    private String name;

    @OneToMany
    @Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN})
    @JoinTable(name="ExposureRules", joinColumns={@JoinColumn(name="TypeId")})
    private Set<ExposureRule> rules;

ExposureRule类:

@Entity
@Table(name="ExposureRules")
public class ExposureRule {

    @Id
    private int id;

    @Column(nullable=false)
    private int inclusive;

    @CollectionOfElements(fetch=FetchType.LAZY)
    @Cascade(CascadeType.ALL)
    @JoinTable(name="ExposureRuleAttributes",joinColumns=@JoinColumn(name="RuleId"))
    @IndexColumn(name="Attribute")
    @Column(name="Value")
    private Map<String, String> attributes = new HashMap<String, String>();

1 个答案:

答案 0 :(得分:0)

我发现了问题。这是@JoinTable的以下行:

@JoinTable(name="ExposureRules", joinColumns={@JoinColumn(name="TypeId")})

我只需要一个@JoinColumn:

@JoinColumn(name="TypeId")