@UniqueConstraint annotation in Java

后端 未结 8 1555
囚心锁ツ
囚心锁ツ 2020-12-02 05:20

I have a Java bean. Now, I want to be sure that the field should be unique.

I am using the following code:

@UniqueConstraint(columnNames={\"username\         


        
相关标签:
8条回答
  • 2020-12-02 05:49

    I'm currently using play framework too with hibernate and JPA 2.0 annotation and this model works without problems

    @Entity
    @Table(uniqueConstraints={@UniqueConstraint(columnNames = {"id_1" , "id_2"})})
    public class class_name {
    
    @Id
    @GeneratedValue
    public Long id;
    
    @NotNull
    public Long id_1;
    
    @NotNull
    public Long id_2;
    
    }
    

    Hope it helped.

    0 讨论(0)
  • 2020-12-02 05:50

    You can use at class level with following syntax

    @Entity
    @Table(uniqueConstraints={@UniqueConstraint(columnNames={"username"})})
    public class SomeEntity {
        @Column(name = "username")
        public String username;
    }
    
    0 讨论(0)
  • 2020-12-02 05:55

    you can use @UniqueConstraint on class level, for combined primary key in a table. for example:

     @Entity
     @Table(name = "PRODUCT_ATTRIBUTE", uniqueConstraints = {
           @UniqueConstraint(columnNames = {"PRODUCT_ID"}) })
    

    public class ProductAttribute{}

    0 讨论(0)
  • 2020-12-02 05:57

    Way1 :

    @Entity
    
    @Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames = "column1"),@UniqueConstraint(columnNames = "column2")})
    

    -- Here both Column1 and Column2 acts as unique constraints separately. Ex : if any time either the value of column1 or column2 value matches then you will get UNIQUE_CONSTRAINT Error.

    Way2 :

    @Entity
    
    @Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})
    

    -- Here both column1 and column2 combined values acts as unique constraints

    0 讨论(0)
  • 2020-12-02 06:01
       @Entity @Table(name = "stock", catalog = "mkyongdb",
       uniqueConstraints = @UniqueConstraint(columnNames =
       "STOCK_NAME"),@UniqueConstraint(columnNames = "STOCK_CODE") }) public
       class Stock implements java.io.Serializable {
    
       }
    

    Unique constraints used only for creating composite key ,which will be unique.It will represent the table as primary key combined as unique.

    0 讨论(0)
  • 2020-12-02 06:04

    To ensure a field value is unique you can write

    @Column(unique=true)
    String username;
    

    The @UniqueConstraint annotation is for annotating multiple unique keys at the table level, which is why you get an error when applying it to a field.

    References (JPA TopLink):

    • @UniqueConstraint
    • @Column
    0 讨论(0)
提交回复
热议问题