I have an entity called Author like the one below. I want to add a unique constraint on the field "name".
@Entity
@Table(name = "author")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "author")
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column( name = "name")
private String name;
@Column(name = "birth_date")
private LocalDate birthDate;
The JHipster generator lacks of the option to generate unique fields for entities. To do it manually:
I have only tested this in MySQL and PostgreSQL and I do remember having read somewhere that this won't work with certain NoSQL databases. That may also be the reason why it is not included in JHipster. But don't quote me on it.
When I did the above, it worked, but when I try to add a duplicate entry, I got the error: Internal Server Error on the client side. This is too generic error and I want to customize it. So I did the following:
1) Edited myapp.web.rest.errors.ErrorConstants.java and added this line to add a new error constant:
public static final String ERR_VALIDATION_DUPLICATE = "entity.validation.duplicate";
2) Edited myapp.web.rest.errors.ExceptionTranslator.java to add my error translator
@ExceptionHandler(DataIntegrityViolationException.class)
@ResponseBody
@ResponseStatus(HttpStatus.CONFLICT)
public ErrorVM processDataIntegrityViolationException(DataIntegrityViolationException exception) {
return new ErrorVM(ErrorConstants.ERR_VALIDATION_DUPLICATE, exception.getMessage());
}
3) Edited src/main/webapp/i18n/en/global.json and added
"entity": {
...
"validation": {
...
"duplicate": "This value is duplicate to existing data.",
...
}
to match the key generated by error mapping on the server side. You need to add the same text message but translated to all languages supported.
Notes: If you want to be more specific in the validation exception, You can create your own special exception that extends DataIntegrityViolationException, then catch that generic DataIntegrityViolationException in your resource class and throw your new exception. And of course map it as done in 1, 2 and 3.
This is not a JHipster question, only JPA.
@Column(unique=true)
Please read JPA documentation about @Column
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With