春季数据国际化最佳实践
我有一个包含弹簧数据,jpa和休眠的弹簧mvc项目。我有一个多语言数据库。我设计了我的数据库和实体。我正在寻找按语言查询表的最佳做法。我是否必须编写自定义 jpa 查询,或者是否有一种通用的方法来查询我的表。
如果我在数据库或实体设计上有错误,请警告我。
数据库:
CREATE TABLE translation (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id));
CREATE TABLE translation_text (
translation_id BIGINT UNSIGNED NOT NULL,
lang VARCHAR(2),
text VARCHAR(1000));
ALTER TABLE translation_text
ADD FOREIGN KEY (translation_id)
REFERENCES translation(id);
CREATE TABLE category (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
category_name BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (id));
ALTER TABLE category
ADD FOREIGN KEY (category_name)
REFERENCES translation(id);
本地化字符串实体:
@Embeddable
public class LocalizedString {
private String lang;
private String text;
//Constructors and getter setters...
}
多语言字符串实体:
@Entity
@Table(name = "translation")
public class MultilingualString {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@ElementCollection(fetch = FetchType.EAGER)
@MapKeyColumn(name = "lang_key")
@CollectionTable(name = "translation_text", joinColumns = @JoinColumn(name = "translation_id"))
private final Map<String, LocalizedString> map = new HashMap<String, LocalizedString>();
public MultilingualString() {
}
public MultilingualString(String lang, String text) {
addText(lang, text);
}
public void addText(String lang, String text) {
map.put(lang, new LocalizedString(lang, text));
}
public String getText(String lang) {
if (map.containsKey(lang)) {
return map.get(lang).getText();
}
return null;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
类别实体:
@Entity
@Table(name = "category")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Category extends BaseEntity<Long> implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="category_name")
private final MultilingualString categoryName = new MultilingualString();
public Category(String lang, String categoryName) {
this.categoryName.addText(lang, categoryName);
}
public Category() {
super();
}
@Override
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCategoryName(String lang) {
return this.categoryName.getText(lang);
}
public void setCategoryName(String lang, String categoryName) {
this.categoryName.addText(lang, categoryName);
}
}
类别存储库:
public interface CategoryRepository extends JpaRepository<Category, Long>{
}
如何将语言参数传递给该语言并获取该语言特殊数据?CategoryRepository