How do I restrict multiple columns using JPA annotations?

I am trying to introduce a multi-key constraint for a JPA-mapped object:

public class InventoryItem { @Id private Long id; @Version private Long version; @ManyToOne @JoinColumn("productId") private Product product; @Column(nullable=false); private long serial; } 

In principle, a (commodity, consecutive) pair should be unique, but I found a way to say that the serial number should be unique. This is obviously not a good idea, as different products may have the same serial numbers.

Is there a way to generate this restriction via JPA or am I forced to manually create it in DB?

+46
java mapping jpa
May 05 '10 at 10:46
source share
2 answers

You can declare unique constraints using the @Table(uniqueConstraints = ...) annotation in your entity class, i.e.

 @Entity @Table(uniqueConstraints={ @UniqueConstraint(columnNames = {"productId", "serial"}) }) public class InventoryItem { ... } 

Note that this does not magically create a unique constraint on the database; you still need DDL to create it. But it looks like you are using some kind of automated tool to create a database based on JPA entity definitions.

+103
May 05 '10 at 10:56 a.m.
source share

As already mentioned, a multi- @Table index can be added using the @Table annotation. However, columnNames must be the name of the actual database columns, not a class attribute. So, if the column looks like this:

 @Column(name="product_id") Long productId; 

Then the @Table annotation should look like this:

 @Table(uniqueConstraints= @UniqueConstraint(columnNames = {"product_id", "serial"}) 
+32
Aug 14 '14 at 19:03
source share



All Articles