I18n for custom error messages into JPA entity

795 views Asked by At

I looking to understand how to internationalize JPA entity error message. I understand how its work into a controller using autowired MessageSource but in my case I want to do this into a JPA entity. I'm not intresting about using the same way as the controller issue because I think is not optimized to autowired the full MessageSource on this entity. If someone have a simple example to show me how its work with a simple entity like mine. My project using spring-boot 2.2 ; JPA ; and thymeleaf.

The entity I using:

package com.bananasplit.weblab2.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

@Entity
@Table(name = "todo")
public class Todo {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Column(name = "name", nullable = false)
    @NotEmpty
    @Size(min=2, max=30) // error message is already internationalized here with spring-boot
    private String name;

    @Column(name = "category", nullable = false)
    @NotEmpty
    @Pattern(regexp="(WORK|PERSONAL|SPECIAL)",
        message="Category must be WORK or PERSONNAL or SPECIAL.") // here is the message I want to internationalize
    private String category;


    public Todo() {}

    public Todo(String name, String category) {
        this.name = name;
        this.category = category;
    }

    @Override
    public String toString() {
        return String.format(
            "Todo[id=%d, name='%s', category='%s']",
            id, name, category);
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }
}
1

There are 1 answers

1
Jonathan JOhx On BEST ANSWER

By default Spring boot uses this ValidationMessages.properties but you can override by adding this file in resources.

@Size(min=2, max=30, message="{empty.todo.name") 
private String name;

In ValidationMessages.properties file

 empty.todo.name = Cannot be blank

If you want to manage which package messages should be scanned by Spring then should follow this link