11

How to make a field unique in pojo using spring data jpa?I know how to do that using jpa

For reference: multi column constraint with jpa

If there is a way, is it possible to use with spring boot?

Community
  • 1
  • 1

4 Answers4

15

Use the @UniqueConstraint annotation to specify that a unique constraint is to be included in the generated DDL for a primary or secondary table.

Alternately, to ensure a field value is unique you can write

@Column(unique=true)
String myField;
Rahul
  • 15,979
  • 4
  • 42
  • 63
2

With Spring Data JPA you are using JPA, so you specify the unique constraint using JPA. Nothing special from Spring Boot or Spring Data on that front.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
1

If you have a single column in the table that has UNIQUE KEY constraint then you can simply add the attribute unique=true in the annotation @Column

CODE SNIPPET:

@Column(name = "unique_key_field", nullable = false, unique = true)
String uniqueKeyFied;

In case if you have multiple Unique key constraints in the table then you have to simply follow with the JPA annotations as the spring-boot-data-starter does not provide any special annotations for the table constraints(KEY/UNIQUEKEY).

CODE SNIPPET:

@Entity
@Table(name = "table_name", uniqueConstraints={
          @UniqueConstraint( name = "idx_col1_col2",  columnNames ={"col1","col2"})
       })
Prasanth Rajendran
  • 4,570
  • 2
  • 42
  • 59
0

Um exemplo em Kotlin:

Entity
@Table(name = "TBL_XXX",
    uniqueConstraints = [
            UniqueConstraint(name = "sessionid_uindex", columnNames = ["sessionId"])
    ]
)
data class XxxReturn(
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "XXX_ID")
    var id: Long? = null,

    var sessionId: String,

    var msg: String
)
Valdemar
  • 422
  • 4
  • 6