Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to introduce multi-column constraint with JPA annotations?

Tags:

java

mapping

jpa

I am trying to introduce a multi-key constraint on a JPA-mapped entity:

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

Basically (product, serial) pair should be unique, but I only found a way to say that serial should be unique. This obviously isn't a good idea since different products might have same serial numbers.

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

like image 561
plouh Avatar asked May 05 '10 10:05

plouh


People also ask

How do I make two columns unique in JPA?

A unique constraint can be either a column constraint or a table constraint. At the table level, we can define unique constraints across multiple columns. JPA allows us to define unique constraints in our code using @Column(unique=true) and @UniqueConstraint.

What is @basic annotation in JPA?

We can use the @Basic annotation to mark a basic type property: @Entity public class Course { @Basic @Id private int id; @Basic private String name; ... } In other words, the @Basic annotation on a field or a property signifies that it's a basic type and Hibernate should use the standard mapping for its persistence.

What is @column annotation in spring boot?

@Column annotation is used for Adding the column the name in the table of a particular MySQL database. Syntax: @Column(name=”DESC”, nullable=false, length=512) public String getDescription() {


1 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 the unique constraint in the database, you still need a DDL for it to be created. But seems like you are using some sort of automated tool for creating the database based on JPA entity definitions.

like image 182
psp Avatar answered Sep 28 '22 08:09

psp