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?

rostbot
  • 342
  • 3
  • 12

1 Answers1

0

You can define any custom DDL in hbm mappings using <database-object>. You can create unique constraints there; hbm2ddl will execute it.

Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110
  • Depends how the abstract superclass is mapped. If the abstract class is mapped to a table with `@Entity` rather than being a `@MappedSuperclass` I believe it is not possible to create such a uniqueness constraint that is enforced by the database. In this case you probably have to enforce it programmatically within your Entity or an EntityListener but i think performance would be pretty poor. – Dave Jul 04 '22 at 00:21