【发布时间】:2016-08-02 11:25:18
【问题描述】:
我写了一个属性转换器。我想在实体中应用它。到目前为止,我遵循的是纯 XML 方法。
我在 hbm 表示法中找不到 @Convert 的等价物。
一个例子将不胜感激。
当我搜索这个时,可以理解的是,Google 会返回很多关于“自动将 hbm 文件转换为实体,反之亦然”的工具/方法的结果。
编辑: 现在我怀疑 hbm 文件中是否有一个选项,因为这是 JPA 注释。
@Convert 的文档说:
Convert注解用于指定Basic的转换 领域或财产。没有必要使用 Basic 注释或 相应的 XML 元素来指定基本类型。
我不完全确定这意味着什么。在这种情况下混合注释和 XML 是一种方法吗?
我试过了:
public class Person {
//this is enum
private Ethnicity ethnicity;
//.....
}
public enum Ethnicity{
INDIAN("IND"),
PERSIAN("PER")
//...constructors and value field.
public String value(){
return this.value;
}
public Ethnicity fromValue(String value){
//logic for conversion
}
}
转换器:
@Converter
public class EthnicityConverter implements AttributeConverter<Ethnicity,String> {
@Override
public Ethnicity convertToEntityAttribute(String attribute) {
if ( attribute == null ) {
return null;
}
return Ethnicity.fromValue( attribute );
}
@Override
public String convertToDatabaseColumn(Ethnicity dbData) {
if ( dbData == null ) {
return null;
}
return dbData.value();
}
}
HBM 文件:
//....other columns
<property name="ethnicity">
<column name="ethnicity"/>
<type name="EthnicityConverter"/>
</property>
//....other columns
编辑:更正了转换器代码。
【问题讨论】:
-
JPA 不使用休眠配置文件。它使用
orm.xml。如果您不使用 JPA,请删除 JPA 标签 -
@NeilStockton 我用的是hibernate,相信hibernate也是JPA的一个实现,Convert来自javax.persistence。我对吗?如果还是有问题,我会删除。谢谢。我们在 hbm 文件中有 EnumType.ORDINAL, STRING 的等价物,因此问题。
-
是的,Hibernate 确实实现了 JPA,但 JPA 不使用“hbm”文件。 JPA 使用 orm.xml。如果您使用的是 hbm 文件,那么您只使用了 HIBERNATE。
-
我删除了,以为有 javax.persistence.Convert,以防这会出现在关注 JPA 的人的提要上。 JPA 涉及到一个元素,有些人可能知道答案。它是重叠的。
-
如果使用 orm.xml 的“convert”定义在此链接datanucleus.org/products/accessplatform_5_0/jpa/…