Hibernate annotations @Table @UniqueConstraint inheritance

1k views Asked by At

I have a Java model for Hibernate where the mapping is done via annotations.
I have an abstract @MappedSuperClass which contains properties that need to be unique so I used the @Table annotation with some @UniqueConstraint.

My problem is that the constraints are not inherited by the children. It works well if I copy/paste the unique constraints in every child class but it seems to me that a cleaner solution should exist :)

Here is the relevant code:

@MappedSuperClass
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"firstname", "lastname"}))
public abstract class Person {
  private String firstname;
  private String lastname;

  // Constructors/Getters/Setters
}

@Entity
@Table(name = "employee")
public class Employee extends Person {
  // Some specific properties, constructors, getters/setters
}

@Entity
@Table(name = "partner")
public class Partner extends Person {
  // Some specific properties, constructors, getters/setters
}


public void testCase() {
  Employee employee1 = new Employee("John", "Doe");
  Employee employee2 = new Employee("John", "Doe");

  this.employeeDAO.save(employee1);
  this.employeeDAO.save(employee2); // I'd like an exception here!
}

Is there a way to get that constraint working without duplicating it in every child class?

Thanks for your help!

0

There are 0 answers