2

Let's say I have already created my Database in Oracle. One of my Tables has the following statement:

CREATE UNIQUE INDEX "SOME_NAME" ON "SOME_TABLE_NAME" (COLUMN1,COLUMN2)

I want to make sure that my hibernate entity is aware of that.

  • Looks like @UniqueConstraint annotation can't be used here because of it is only used if table generation is in effect.
  • Also I noticed that CREATE UNIQUE INDEX "SOME_NAME" ON "SOME_TABLE_NAME" (COLUMN1,COLUMN2) is not working in my H2 database.

Is there a way to make sure that my entity will be aware of that restriction?

Columb1a
  • 463
  • 2
  • 11
  • 25
  • No your Entity cannot be made aware of it. You can however add some form of validation that checks the condition before write to the database, perhaps a custom JSR303 validation. See for example: http://stackoverflow.com/questions/17092601/how-to-validate-unique-username-in-spring – Alan Hay Oct 05 '16 at 16:39
  • @AlanHay So now I'm wondering if it is not enough to add the constraint just in Oracle. So with that the values that are being pulled from the DB to the entity are already validated. aren't they? – Columb1a Oct 05 '16 at 16:57
  • If you are saving user entered data and a UK is violated then the stack trace is unlikely to help you identify what went wrong and present a meaningful error message. This is where Java validation would be useful. – Alan Hay Oct 05 '16 at 17:01

1 Answers1

1

The @Table annotation in JPA/Hibernate allows for a uniqueConstraints attribute. This allows you to make your entity aware of the constraint.

@Table(name="SOME_TABLE_NAME",
  uniqueConstraints = {@UniqueConstraint(columnNames={"COLUMN1", "COLUMN2"})}
)
M. Rizzo
  • 1,611
  • 12
  • 24
  • Yes, But looks like the UniqueConstraint can be used just when you want to create your DB Schema through Hibernate: `/** * (Optional) Unique constraints that are to be placed on the * table. These are only used if table generation is in effect. * These constraints apply in addition to primary key constraints. *

    * Defaults to no additional constraints. */ UniqueConstraint[] uniqueConstraints() default { };` At least from my side `@UniqueConstrainst` didn't have any effect.
    – Columb1a Oct 05 '16 at 15:46
  • Yes correct without auto generation this is merely additional information (annotated classes). You would need to create the constraint manually on the database engine. And as @AlanHay has indicated the stack trace returned from the persistence exception may not make it entirely clear what went wrong. I also agree that yes you may want to add some Java validation and return a meaningful validation error message. – M. Rizzo Oct 05 '16 at 18:00