How to name a Hibernate/JPA Constraint?

Asked

Viewed 1,712 times

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, rather than come fk_8pxwdacx0r81ra9d59m6erkri, name as Pais_Pessoa and uk_4tdehxj7dh8ghfc68kbwbsbll, name as unique_nome.

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

2 answers

6


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

If I wanted to apply the same example to Constraint involving more than one column:

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

Complementing

In the case of Foreign Key just use the Annotation @Foreignkey:

@OneToOne
@JoinColumn(name = "idPais", nullable = true)
@ForeignKey(name="Pais_Pessoa")
private Pais pais;
  • Just to finish(an extra question), in case I want to assign a different name to each uniqueConstraint can do so @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"nome", "email"}, name = {"unique_nome", "unique_email"}))? Or do I have to create another Annotation? And how do I also put conditions?

  • 1

    In case you can create an array of uniqueConstraints, it would look like this: @Table(name="table", uniqueConstraints={
 @UniqueConstraint(columnNames="nome," name="unique_nome", ),
 @UniqueConstraint(columnNames="email", name="unique_email")
})

  • Thank you was very helpful

0

Complementing @jhonnyvsilvab’s reply as the code is deprecated. For foreign key, 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;
  • 2

    Hello @Ri Welcome to Stackoverflow, this only answers part of the question.

  • 1

    The reply of @jhonnyvsilvab is already quite complete. I commented only to complement it, since the mode indicated for foreign key is deprecated. I did not do it as a comment in his reply, as I do not have points for it yet. That said, I would like to review the evaluation of my comment.

  • Right. The proposed edition helped in understanding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.