我有两个实体,其中包含我想要本地化的字段。但是,我不确定如何正确实现它,因为我需要对实体的引用以及对已翻译字段的引用,以便拥有共享的“i18n”表。
@Entity
public class EntityA {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Translation> name;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Translation> description;
}
第二个实体
@Entity
public class EntityB {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Translation> name;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Translation> shortDescription;
}
翻译实体
@Entity
@Table(name = "i18n")
public class Translation {
private String languageCode;
private String translation;
//private String referenceToEntity
//private String referenceToField
}
是否有一种给定的方法可以在 Spring 中启用实体字段的国际化,或者至少有某种解决方法可以使其在没有太多开销的情况下工作?
编辑
我写了一篇简短的文章,介绍如何使用 XmlAnyAttribute https://overflowed.dev/blog/dynamical-xml-attributes-with-jaxb/ 解决它。
最佳答案
我做了一些研究,发现了这个 @Convert JPA 注释。您需要将名称和描述属性封装到一个对象(实现 AttributeConverter)中,并使用转换类来指定持久化时如何翻译以及检索时如何翻译。
要执行持久性和检索的翻译,您可以使用 Google translate's API 。
这里:
@Entity
public class EntityA {
@Convert(converter = DescriptionConverter.class)
private Description description
// getters and setters
},
封装的对象,类似于:
public class Description {
private String name;
private String language;
private String description;
// Getters and Setters.
}
翻译适用于此:
@Converter
public class DescriptionConverter implements AttributeConverter<Description, String> {
@Override
public String convertToDatabaseColumn(Description description) {
// consume Google API to persist.
}
@Override
public Document convertToEntityAttribute(String description) {
// consume Google API to retrieve.
}
}
关于java - Spring Hibernate 中实体字段的本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56752756/