How to introduce multi-column constraint with JPA annotations?

前端 未结 2 1918
迷失自我
迷失自我 2020-11-28 10:54

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

public class InventoryItem {
    @Id
    private Long id;

    @Version 
    private          


        
相关标签:
2条回答
  • 2020-11-28 11:21

    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.

    0 讨论(0)
  • 2020-11-28 11:33

    As already answered, multi-column index can be added using @Table annotation. However, columnNames needs to be the name of actual DB columns, not the class attribute. So, if the column is like the following:

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

    Then the @Table annotation should be like the following

    @Table(uniqueConstraints=
           @UniqueConstraint(columnNames = {"product_id", "serial"}) 
    
    0 讨论(0)
提交回复
热议问题