2017-04-18 1 views
1

DATE 필드를 데이터베이스에서 읽을 때 해당 개체를 java.time.LocalDate 개체로 강제 변환 할 수있는 변환기를 만들었습니다. DATE에서 java.time.LocalDate까지 JPA 변환기가 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

유형 DATE입니다 열 START_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(); 
    } 
} 
:

그래서, 이런 식으로 뭔가에 컨버터를 업데이트하는 트릭을 할해야

관련 문제