2017-04-18 112 views
1

我做了一個轉換器,當我從數據庫中讀取日期字段時,它應該能夠強制它們到java.time.LocalDate對象。然而,當我嘗試這樣做,它給了我這個錯誤:JPA轉換器從日期到java.time.LocalDate不適用Glassfish 4.1

The object [3/16/17 12:00 AM], of class [class java.sql.Timestamp], from mapping [org.eclipse.persistence.mappings.DirectToFieldMapping[startDate-->TEST_TABLE.START_DATE]] with descriptor [RelationalDescriptor(com.test.TestEntity --> [DatabaseTable(TEST_TABLE)])], could not be converted to [class [B]. 

TEST_TABLE是我的表,其中有一列START_DATE這是DATE類型。這裏是轉換器:

import javax.persistence.AttributeConverter; 
import javax.persistence.Converter; 
import java.sql.Date; 
import java.time.LocalDate; 

@Converter(autoApply = true) 
public class OracleLocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> { 
    @Override 
    public Date convertToDatabaseColumn(LocalDate attribute) { 
     return (attribute != null ? Date.valueOf(attribute) : null); 
    } 

    @Override 
    public LocalDate convertToEntityAttribute(Date dbData) { 
     return (dbData != null ? dbData.toLocalDate() : null); 
    } 
} 

爲什麼它認爲我的專欄是時間戳?在oracle中的所有日期都被強制爲java.sql.Timestamp

回答

1

java.sql.Timestamp是持久性提供程序用來解析來自DB的日期而不管該值是否僅僅是日期的類。這很有意義,因爲它允許持久性提供者獲取DATETIME或TIMESTAMP的時間部分。請注意,此課程從java.util.Date延伸而不是java.sql.Date

所以,更新您的轉換器這樣的事情應該做的伎倆:

import java.time.LocalDate; 
import java.time.ZoneId; 
import java.util.Date; 
import javax.persistence.AttributeConverter; 
import javax.persistence.Converter; 

@Converter(autoApply = true) 
public class OracleLocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> { 

    @Override 
    public Date convertToDatabaseColumn(LocalDate attribute) { 
     return attribute == null ? null : Date.from(attribute.atStartOfDay(ZoneId.systemDefault()).toInstant()); 
    } 

    @Override 
    public LocalDate convertToEntityAttribute(Date dbData) { 
     return dbData == null ? null : dbData.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); 
    } 
}