使用JPA在包装器对象上映射单向OneToMany关联

时间:2011-10-18 19:57:43

标签: jpa

我正在将Hibernate配置转换为使用JPA。当前配置有一个AlertPref类(ALERT_PREF表),其中包含一组Long类型,这些类型是ALERT_CATEGORY表中的主键值。有一个ALERT_PREF_CATEGORY连接表连接这两个。我可以在JPA中通过将联结表定义为Entity类并在AlertPref类中使用AlertPrefCategory对象而不是Long ID来设置此关系,但我希望尽可能避免这种情况,而是设置单向映射AlertPref为长ID。一些遗留代码使用ID,并且很难更改此代码。

这是Hibernate配置中的当前类标记,可以正常工作:

<class name="AlertPref" table="ALERT_PREF">
    <id name="alertPrefId" column="ALERT_PREF_ID" type="long">
        <generator class="hilo">
            <param name="max_lo">100</param>
        </generator>
    </id>

    <property name="userId" column="USER_ID" type="string"
        not-null="true" />

    <set name="excludedCategoryIds" table="ALERT_PREF_CATEGORY" cascade="all,delete-orphan">
        <key column="ALERT_PREF_ID" />
        <element column="EXCLUDED_CATEGORY_ID" type="long" />
    </set>

</class>

以下是我在JPA中尝试使用的内容,但它抛出异常“使用@OneToMany或@ManyToMany定位未映射的类:AlertPref.excludedCategoryIds [java.lang.Long]”

@Entity
@Table(name = "ALERT_PREF")
public class AlertPref {
    @Id
    @TableGenerator(name = "table_gen", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "table_gen")
    @Column(name = "ALERT_PREF_ID")
    private long alertPrefId;

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

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinTable(name = "ALERT_PREF_CATEGORY", 
        joinColumns = @JoinColumn(name = "ALERT_PREF_ID"), 
        inverseJoinColumns = @JoinColumn(name = "EXCLUDED_CATEGORY_ID"))
    private Set<Long> excludedCategoryIds;

    /**
     * @return Returns the alertPrefId.
     */
    public long getAlertPrefId() {
        return alertPrefId;
    }

    /**
     * @param alertPrefId
     *            The alertPrefId to set.
     */
    public void setAlertPrefId(long alertPrefId) {
        this.alertPrefId = alertPrefId;
    }

    /**
     * @return Returns the userId.
     */
    public String getUserId() {
        return userId;
    }

    /**
     * @param userId
     *            The userId to set.
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * @return the excludedCategoryIds
     */
    public Set<Long> getExcludedCategoryIds() {
        return excludedCategoryIds;
    }

    /**
     * @param excludedCategoryIds the excludedCategoryIds to set
     */
    public void setExcludedCategoryIds(Set<Long> excludedCategoryIds) {
        this.excludedCategoryIds = excludedCategoryIds;
    }
}

1 个答案:

答案 0 :(得分:0)

您必须使用ElementCollection和CollectionTable注释,如Hibernate reference documentation中所述。