@UniqueConstraint annotation in Java

后端 未结 8 1556
囚心锁ツ
囚心锁ツ 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 06:04

    Unique annotation should be placed right above the attribute declaration. UniqueContraints go into the @Table annotation above the data class declaration. See below:

    @Entity
    @Table(uniqueConstraints= arrayOf(UniqueConstraint(columnNames = arrayOf("col_1", "col_2"))))
    data class Action(
            @Id @GeneratedValue @Column(unique = true)
            val id: Long?,
            val col_1: Long?,
            val col_2: Long?,
    )
    
    0 讨论(0)
  • 2020-12-02 06:08

    Note: In Kotlin the syntax for declaring the arrays in annotations uses arrayOf(...) instead of {...}

    @Entity
    @Table(uniqueConstraints=arrayOf(UniqueConstraint(columnNames=arrayOf("book", "chapter_number"))))
    class Chapter(@ManyToOne var book:Book,
                  @Column var chapterNumber:Int)
    

    Note: As of Kotlin 1.2 its is possible to use the [...] syntax so the code become much simpler

    @Entity
    @Table(uniqueConstraints=[UniqueConstraint(columnNames=["book", "chapter_number"])])
    class Chapter(@ManyToOne var book:Book,
                  @Column var chapterNumber:Int)
    
    0 讨论(0)
提交回复
热议问题