我正在尝试将数据库中的类型转换为另一种类型,以便在我的实体中使用。通过一些研究,我发现了JPA2.1中定义的AttributeConverter类。
我的类都是从Avro生成的,所以不会使用JPA/HBM注释
使用hbm.xml文件映射所有类,而不是实体映射所有数据库连接读取和写入工作。因此,hbm配置是正确的,只是存在类型转换问题。
Relevant Tech Stack
-
HB Version: 4.3.11.Final
JPA Version: 2.1我尝试简单地将转换器添加为
这是我唯一能想到去尝试的事情。在我的实现中不能使用的注释之外
class.hbm.xml
<hibernate-mapping default-lazy="false">
<class name="ACLASS" table="CASE">
<id name="id" type="long" column="id">
<generator class="native"/>
</id>
<property name="aColumn" type = "dao.converter.DateToLongConverter" column = "A_COLUMN" />
</class>
</hibernate-mapping>DateToLongConverter.java忽略占位符逻辑!
@Converter(autoApply=true)
public class DateToLongConverter implements AttributeConverter<Long, java.sql.Date> {
@Override
public java.sql.Date convertToDatabaseColumn(Long millitime) {
System.out.println(millitime);
return new Date(1);
}
@Override
public Long convertToEntityAttribute(java.sql.Date dbData) {
System.out.println(dbData.toString());
return 1L;
}
}以上代码的结果只是一个例外:Could not determine type for: dao.converter.DateToLongConverter, at table: ATABLE, for columns: [org.hibernate.mapping.Column(A_COLUMN)]
我还尝试添加META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence
version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="case-consumer-persistence">
<class>dao.converter.DateToLongConverter</class>
<class>aClass</class>
</persistence-unit>
</persistence>发布于 2019-07-10 03:24:58
我从未用.xml配置定义过持久化实体,但我希望它能有所帮助:
您正在为"aColumn“定义一个类型dao.converter.DateToLongConverter,但实际上,您应该为它定义一个转换器。您提到的类型应该是您在代码中使用的类型对象:在您的示例中,您的类型应该是Long。
另一个answer将帮助您在xml config上定义您的转换器。这只是类型名称的另一种格式。
这就是用注解定义@Convert的方式。您应该正在寻找在您的hbm上复制此模板。
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Convert(converter = DateToLongConverter.class)
private Long aColumn;
}https://stackoverflow.com/questions/56956055
复制相似问题