How to name a constraint in Hibernate / JPA?

2

Using the class:

@Entity
public class Pessoa{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idPessoa;

    @Column(nullable=false, unique = true)
    private String nome;

    @OneToOne
    @JoinColumn(name = "idPais", nullable = true)
    private Pais pais;

    public Pessoa(){}

    // Getters and Setters

}

In the bank is generated

CONSTRAINT fk_8pxwdacx0r81ra9d59m6erkri FOREIGN KEY (idpais)

CONSTRAINT uk_4tdehxj7dh8ghfc68kbwbsbll UNIQUE (nome)

How to name, instead of fk_8pxwdacx0r81ra9d59m6erkri , name Pais_Pessoa and uk_4tdehxj7dh8ghfc68kbwbsbll , name unique_nome .

Is this possible in JPA / Hibernate? If so, how?

    
asked by anonymous 30.03.2016 / 14:44

2 answers

6

You can do this by modifying the properties of the @table annotation. Here's the example for the 'unique_name':   @Table(uniqueConstraints = @UniqueConstraint(columnNames = "nome", name = "unique_nome"))

If you wanted to apply the same example to constraints involving more than one column:

@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"nome", "email"}, name = "nome_email"))

Complementing

For Foreign Key, just use the annotation @ForeignKey:

@OneToOne
@JoinColumn(name = "idPais", nullable = true)
@ForeignKey(name="Pais_Pessoa")
private Pais pais;
    
30.03.2016 / 15:08
0

Complementing @jhonnyvsilvab's answer, because the code is deprecated . For foreign keys, do:

import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

...

@OneToOne
@JoinColumn(name = "idPais", nullable = true, foreignKey = @ForeignKey(name = "UK_PAIS_PESSOA"))
private Pais pais;
    
23.10.2018 / 20:24