How to use @UniqueConstraint with single table inheritance (JPA)?
Asked Answered
H

1

3

I have a class extending an existing entity with single table strategy (which I can't change). I want to use UniqueConstraint for that entity so I tried:

@Entity
@Table(name = "t_document")
public class Document implements Serializable {
...
}

and

@Entity
@Table(uniqueConstraints = { @UniqueConstraint(name = "Test", columnNames = { ...  }) })
public class MyDocument extends Document {
...
}

The unique constraint is not used at all, nothing in log file. Is this the correct way to use UniqueConstraints in this situation?

(We use JPA2, JBoss 7.1)

Homer answered 2/1, 2015 at 10:49 Comment(2)
How do you generate your classes? The @UniqueConstraint only works for the generation of tables,Cohesion
Tables are created via Hibernate / JPA <property name="hibernate.hbm2ddl.auto">create</property>. The table is created correctly, only the constraint is missing.Homer
E
2

You cannot override the base class @Table declaration, that's why the sub-class uniqueConstraints directive is ignored.

With JPA you can override annotations with xml declarations. So you need to add an orm.xml file in your class-pat and add the unique constraints there:

<entity-mappings 
  xmlns="http://java.sun.com/xml/ns/persistence/orm"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
  version="2.0">

    <package>...</package>
    <entity class="Document" access="PROPERTY" metadata-complete="false">
        <table name="document">
            <unique-constraint>
                <column-name>first_column</column-name>
                <column-name>second_column</column-name>
            </unique-constraint>
        </table>            
</entity-mappings>

This way you might not even need the MyDocument sub-class, if you only used it to override the DDL schema.

Ellie answered 2/1, 2015 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.