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

I have a class extending an existing object with one table strategy (which I cannot change). I want to use UniqueConstraint for this object, 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 restriction is not used at all, nothing in the log file. Is this the right way to use UniqueConstraints in this situation?

(We use JPA2, JBoss 7.1)

+2
java hibernate jpa unique-constraint single-table-inheritance
source share
1 answer

You cannot override the declaration of the base class @Table, so the uniqueConstraints directive for the subclass is ignored.

With JPA, you can override annotations with xml declarations . Therefore, you need to add the orm.xml file to your pat class and add unique restrictions 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> 

Thus, you may not need to subclass the MyDocument class if you used it only to override the DDL schema.

+2
source share

All Articles