[英]How to persist LocalDate into Hibernate as a Date type
我想將LocalDate
作為Date
類型保留到Hibernate
,但即使在 Hibernate 文檔中也找不到它。 我試過一次,但它存儲為 blob 類型。
這是我的票務實體:
<?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
但我不知道如何將該類與我的實體連接起來。
您必須創建一個轉換器:
@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 文件中,您將轉換器添加為該屬性的類型:
<property name="date" column="tb_date" type="date"/>
<convert converter="com.mypkg.MyConverter" attribute-name="date"/>
嘗試這個:
<property name="date" column="tb_date" type="LocalDate" />
請參閱hibernate 5.2 用戶指南中的表 2 Java 8 基本類型。
(我的母語不是英語)
我使用 Hibernate 5.4,我找到了這個問題的答案,這更容易。
您只需將屬性的類型更改為org.hibernate.type.LocalDateType
。
這也適用於 LocalDateTime,您只需要將類型更改為org.hibernate.type.LocalDateTimeType
。
對於任何其他類型,您應該考慮查看org.hibernate.type
。
雖然帖子很舊,但如果有人試圖在 hbm 中使用 LocalDate 和 hibernate,仍然會回復。 為了使用@Maciej Kowalski 編寫的轉換器,應該使用 hbm 文件中的以下條目,如 hibernate docs Example 28. HBM mapping for AttributeConverter “要使用 HBM 配置文件映射 MoneyConverter,您需要使用轉換后的文件: : 屬性元素的類型屬性中的前綴。”
<property name="birthDate" column="birth_date"
type="converted::com.mypkg.LocalDateConverter"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.