8

I have a requirement in which many of my entities need a Long value and a @ManyToOne relationship with some other entity. This requirement can be easily achieved with a MappedSuperclass in the following way:

    @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 the entity combination must be unique. Is it possible to define the index in the superclass? If I define the index in the @Table of the Entity the code works as expected

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

The setback is that the constraint would then have to be replicated along all the child classes and then all changes would also need to be replicated leaving the inheritance almost useless (definitely not as elegant)

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

PS: I know that this is all relevant only when table generation is in effect, its all part of our coding and best practices politics.

Diego Borda
  • 173
  • 1
  • 9

1 Answers1

0

I could type this all out, or I could just give you a link to a solution :)

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

In essence, you cannot override the @Table annotation in extended classes, however, you can set the unique constraints in an orm.xml file (which is referenced from your persistence.xml).

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

Community
  • 1
  • 1
Xaero Degreaz
  • 1,045
  • 11
  • 18