Doubt how to leave a single attribute - JPA

1

I am creating an entity, and I have a CPF field and this field that is unique, how to map this CPF field?

My entity.

@Entity

public class Client {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long codigo;
private String nome;
private String cpf;
private String telefoneFixo;
private String telefoneCelular;
    
asked by anonymous 20.03.2017 / 18:25

2 answers

2

You can do the class level within the @Table annotation, here is an example:

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"cpf"})})
public class Entidade{

    @Column
    public String cpf;
}

Source: link

    
20.03.2017 / 18:32
2

Try it out:

@Column(unique=true)
private String cpf;

EDIT

The suggestion sent by adelmo00 is a better practice than the one I suggested because it allows the definition of one or more fields as unique. If you are sure that only the cpf field needs to be unique then there is no problem in using my suggestion, however, if you later want to define more attributes as unique, so that you are not writing @Column (unique = true) for each field, I recommend using adelmo00's suggestion.

    
20.03.2017 / 18:33