1

In short: Is there a way to write a hibernate xml mapping with a two column unique constraint, where one field of the unique constraint is part of the mapping of an abstract class and another field is defined in the subclass mapping?

Long version: I have a class AbstractCustomFieldValue which references two other classes, some entity RefType and another entity CustomField. AbstractCustomFieldValue has several implementations as shown below.

public abstract class AbstractCustomFieldValue<RefType extends SomeInterface>
{
    protected long id;
    protected RefType refObjekt;
    protected CustomField customField;
    protected String value;
}

public class MyEntityCustomFieldValue extends AbstractCustomFieldValue<MyEntity>
{
}

public class MyOtherEntityCustomFieldValue extends AbstractCustomFieldValue<MyOtherEntity>
{
}

AbstractCustomFieldValue is mapped as an abstract class, the implementations are mapped as subclasses.

<class name="AbstractCustomFieldValue" abstract="true">
    <id name="id">
        <generator class="MyUniqueIdGenerator"/>
    </id>
    <many-to-one name="customField" class="CustomField" column="customfield_id"/>
    <property name="value" length="65535"/>
</class>

<union-subclass name="MyEntityCustomFieldValue" extends="AbstractCustomFieldValue" table="my_entity_customfield_values">
    <many-to-one name="refObjekt" class="MyEntity" column="ref_id"/>
</union-subclass>

<union-subclass name="MyOtherEntityCustomFieldValue" extends="AbstractCustomFieldValue" table="my_other_entity_customfield_values">
    <many-to-one name="refObjekt" class="MyOtherEntity" column="ref_id"/>
</union-subclass>

The combination of refObjekt and customField needs to be unique. Is there a way to achieve this with this mapping?

I still have the option to define a unique key in the database without hibernate or to remove customField from the abstract mapping and to place it into the subclass mapping:

<properties name="myUniqueKey" unique="true">
    <many-to-one name="customField" class="CustomField" column="customfield_id"/>
    <many-to-one name="refObjekt" class="MyEntity" column="ref_id"/>
</properties>

But is there a way to keep customField in the mapping of the abstract class and still to be able to define a hibernate unique constraint?

4

1 回答 1

0

您可以使用<database-object>在 hbm 映射中定义任何自定义 DDL 。您可以在那里创建独特的约束;hbm2ddl 将执行它。

于 2015-09-09T15:20:06.427 回答