休眠 hbm 文件中 @Convert 的等价物是什么?

pin*_*her 5 java enums hibernate

我写了一个属性转换器。我想在实体中应用它。到目前为止,我一直在遵循纯 XML 方法。

@Converthbm符号中找不到等价物。

一个例子将不胜感激。

当我搜索这个时,可以理解的是,谷歌返回了很多关于“将 hbm 文件自动转换为实体反之亦然”的工具/方法的结果。

编辑: 现在我怀疑 hbm 文件中是否有选项,因为这是 JPA 注释。

的文档@Convert说:

Convert 注释用于指定基本字段或属性的转换。不需要使用 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
   }
}
Run Code Online (Sandbox Code Playgroud)

转换器:

@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();
        }
}
Run Code Online (Sandbox Code Playgroud)

HBM 文件:

//....other columns
 <property name="ethnicity">
            <column name="ethnicity"/>
            <type name="EthnicityConverter"/>
        </property>
//....other columns
Run Code Online (Sandbox Code Playgroud)

编辑:更正了转换器代码。

Ste*_*ole 5

Sarvana 的答案很接近——您实际上确实使用了typeXML 属性。但是,type用于命名 Hibernate Type。但是,有一个约定来命名 AttributeConverter - 只需将前缀converted::应用于您的 AttributeConverter FQN。例如,

 <property name="ethnicity">
            <column name="ethnicity"/>
            <type name="converted::EthnicityConverter"/>
 </property>
Run Code Online (Sandbox Code Playgroud)

另一种选择是自动应用转换器:

@Converter( autoApply=true)
public class EthnicityConverter implements AttributeConverter<Ethnicity,String> {
    ...
}
Run Code Online (Sandbox Code Playgroud)

给定上面的转换器,只要 Hibernate 知道它,Hibernate 就会将其应用于任何类型的属性Ethnicity

HTH


Sar*_*ana 2

type是注释的等效 xml 属性Convert

下面是在DB中转换为Y/N,在实体中转换为Boolean。

<property name="status" column="book_status" type="yes_no" not-null="true"/>
Run Code Online (Sandbox Code Playgroud)

只需替换yes_no为您的自定义converter类即可

请参阅我的回答 /sf/answers/2653999001/

官方文档 https://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/ch06.html

更新

<property name="ethnicity" column="ethnicity" type="com.example.EthnicityConverter"/>
Run Code Online (Sandbox Code Playgroud)

更新

@Converter
public class EthnicityConverter implements AttributeConverter<Ethnicity, String> {

    @Override
    public String convertToDatabaseColumn(Ethnicity attribute) {
        // TODO return String value of enum
    }

    @Override
    public Ethnicity convertToEntityAttribute(String dbData) {
        // TODO return resolved enum from string
    }

}
Run Code Online (Sandbox Code Playgroud)