Define @UniqueConstraint in @MappedSuperclass

I have a requirement that many of my entities need a long meaning and @ManyToOne relationship with some other object. This requirement can be easily achieved using MappedSuperclass as follows:

@MappedSuperclass public class BaseEntity { @Column(name = "value", nullable = false) private Long value; @JoinColumn(name = "some_entity_id", nullable = false) @ManyToOne(fetch = FetchType.EAGER) private SomeEntity some; 

The problem is that the long value and combination of objects must be unique. Is it possible to define an index in a superclass? If I define the index in the @Table of the object, the code works as expected

  @UniqueConstraint(name = "uq1", columnNames = {"value", "some_entity_id"}) 

The failure is that the constraint should then be replicated along all child classes, and then all changes should also be replicated, leaving the inheritance almost worthless (definitely not so elegant)

To summarize the real question: is it possible to define a composite unique constraint from @MappedSuperclass? If the answer is NO, what would you do?

PS: I know that all this matters only when table generation is in effect, all of it is part of the coding policy and best practices.

+7
java-ee eclipselink
source share
1 answer

I could print it all, or I could just give you a link to the solution :)

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

Essentially, you cannot override the @Table annotation in extended classes, however you can set unique restrictions in the orm.xml file (referenced by your persistence.xml ).

This means that you can add a unique constraint that will be inherited from all classes that extend your base class.

0
source share

All Articles