我想了解如何国际化 JPA 实体错误消息。我了解它如何使用自动装配的 MessageSource 在控制器中工作,但就我而言,我想在 JPA 实体中执行此操作。我对使用与控制器问题相同的方式并不感兴趣,因为我认为没有针对在该实体上自动装配完整的 MessageSource 进行优化。如果有人有一个简单的例子来向我展示它如何与像我这样的简单实体一起工作。我的项目使用 spring-boot 2.2 ;JPA ; 和百里香叶。
我使用的实体:
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;
}
}