如何将 LocalDate 作为日期类型持久化到 Hibernate [英] How to persist LocalDate into Hibernate as a Date type
问题描述
我想将 LocalDate
作为 Date
类型保存到 Hibernate
中,但即使在 Hibernate 文档中我也找不到它.我试过一次,但它存储为 blob 类型.
I'd like to persist LocalDate
into Hibernate
as a Date
type but I can't find it even in the Hibernate documentation. I've tried once but it is stored as blob type.
这是我的票务实体:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.clustertech.entity">
<class name="Ticket" table="ticket">
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="date" column="tb_date" type="date" length="35"/>
<property name="topic" column="tb_topic" type="string" length="35"/>
<property name="subject" column="tb_subject" type="string" length="35"/>
<property name="status" column="tb_status" type="string" length="35"/>
<property name="message" column="tb_message" type="string" length="255"/>
<many-to-one name="person" column="person_id"/>
</class>
</hibernate-mapping>
这是我的班级实体:
public class Ticket implements Comparable<Ticket> {
private int id;
private LocalDate date;
private String topic;
private String Subject;
private String message;
private String status;
private Person person;
}
它具有作为普通 POJO 类的 getter 和 setter.我在其他网站上看到过一种方法,但他们正在使用注释.我想要类似的东西,但我不使用注释只是普通的 POJO 类和 hbm.xml
文件.我很确定我必须创建另一个类才能将 LocalDate
转换为 Date
但我不知道如何将该类与我的实体连接起来.
It has getters and setters as a normal POJO class. I have seen in other websites one way to do that but they are using anotations. I would like something similar but I am not using anotations just normal POJO class and hbm.xml
files. I'm pretty sure I have to create another class in order to convert LocalDate
into Date
but I don't know how to connect that class with my entity.
推荐答案
你必须创建一个转换器:
You have to create a converter:
@Converter
public class MyConverter implements AttributeConverter<LocalDate, Date> {
@Override
public Date convertToDatabaseColumn(LocalDate localDate) {
if(localDate == null){
return null;
}
return Date.valueOf(localDate);
}
@Override
public LocalDate convertToEntityAttribute(Date date) {
if(date == null){
return null;
}
return date.toLocalDate();
}
}
然后在您的 hbm.xml 文件中,您将转换器添加为该属性的类型:
Then in your hbm.xml file you add you converter as a type of that property:
<property name="date" column="tb_date" type="date"/>
<convert converter="com.mypkg.MyConverter" attribute-name="date"/>
这篇关于如何将 LocalDate 作为日期类型持久化到 Hibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!