3

I'd like to know how can use a validation with a message for unique=true in my entity.

@Entity
@Table(name="employees")
public class Employee implements Serializable {

...

@NotEmpty(message = "it cannot be empty")
@Column(name="identification_number", nullable=false, unique=true)
// a message with (message = "the identification number already exist") but i'dont know how implement
private String numeroIdentificacion;

...
James
  • 77
  • 6
  • I guess you will you have to write your custom validator and own constraint annotation. – Amit kumar Jun 27 '20 at 15:28
  • `@Table(name="employees", uniqueConstraints = { @UniqueConstraint(columnNames = "numeroIdentificacion", name = "uniqueNumero")} )` Did you try something like this? – Govind Jun 27 '20 at 16:42
  • 2
    Does this answer your question? [Add a Custom message for the Unique Constraints in hibernate](https://stackoverflow.com/questions/50466545/add-a-custom-message-for-the-unique-constraints-in-hibernate) – Anish B. Jun 27 '20 at 16:47
  • @Govind Because it is with db columns you need to use the db column name and not the java entity name : `@Column(name="identification_number", nullable=false, unique=true)` => `columnNames = "identification_number"` in your constraint definition inside the `@Table` annotation. – BendaThierry.com Jan 29 '23 at 16:33
  • The best way is just to add a try/catch block inside the call of your service layer inside your controller and raise a binding error if a DataIntegrityViolationException is thrown, or any other exception of your backend services. @see https://stackoverflow.com/a/16172658/390462 – BendaThierry.com Jan 29 '23 at 17:11

1 Answers1

2
 @Column(unique= true)
 @Unique(message="duplicate message")

will give the validation message.

Nayan
  • 311
  • 1
  • 6
  • 1
    Where your `@Unique` annotation is coming from ? There is no `@Unique` annotation in JPA or Hibernate as much as I know. So, if you are creating one with your service layer, beware of phantom reads (Serialization level while JPA transactions are the only way to go safely here). – BendaThierry.com Jan 29 '23 at 16:31