2020-04-23

Hibernate JPA @UniqueConstraint Example

@UniqueConstraint

The @UniqueConstraint annotation is used to specify a unique constraint to be included by the automated schema generator for the primary or secondary table associated with the currently annotated entity.

UniqueConstraint Specifies that a unique constraint is to be included in the generated DDL for a primary or secondary table.
    Example:
    @Entity
    @Table(
        name="EMPLOYEE",
        uniqueConstraints=
            @UniqueConstraint(columnNames={"EMP_ID", "EMP_NAME"})
    )
    public class Employee { ... }

Columns unique constraint
The @UniqueConstraint annotation is used to specify a unique constraint to be included by the automated schema generator for the primary or secondary table associated with the current annotated entity.

Considering the following entity mapping, Hibernate generates the unique constraint DDL when creating the database schema:

 @UniqueConstraint mapping example

@Entity
@Table(
    name = "book",
    uniqueConstraints =  @UniqueConstraint(
        name = "uk_book_title_author",
        columnNames = {
            "title",
            "author_id"
        }
    )
)
public static class Book {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(
        name = "author_id",
        foreignKey = @ForeignKey(name = "fk_book_author_id")
    )
    private Author author;

    //Getter and setters omitted for brevity
}

@Entity
@Table(name = "author")
public static class Author {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    //Getter and setters omitted for brevity
}

No comments:

Post a Comment