The Problem

With Java 8 Oracle brought us LocalDateTime.  With all of its benefits there is a major downer:

LocalDateTime cannot be simply be saved to Database

An Oracle Database  only accepts java.sql.Timestamp but cannot store java.time.LocalDateTime. Of course we dont want to miss out the new API just because of this fact. There is a way to work around that Problem: so called Converters or in this case a LocalDateTimeConverter

LocalDateTimeConverter

Converters take the responsibilty to always make sure that the right type is saved or retrieved from the database.

This is the Code we need

package entity;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<localdatetime, timestamp=""> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime localdatetime) {		
return (localdatetime == null ? null : Timestamp.valueOf(localdatetime));
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {	
return (timestamp == null ? null : timestamp.toLocalDateTime());
}
}</localdatetime,>

by overriding the mehtods we inherited from AttributeConverter we have already solved the problem. I think the code is pretty self speaking

If the autoApply element is specified as true, the persistence provider must automatically apply the converter to all mapped attributes of the specified target type for all entities in the persistence unit except for attributes for which conversion is overridden by means of the Convert annotation (or XML equivalent).

Of course you can write a converter for whatever you want because of generics AttributeConverter<X, T> .

Applying the Converter

We cann now annotate every Attribute of type LocalDateTime with our Converter.
And thats all.

@Convert(converter = LocalDateTimeConverter.class)
private LocalDateTime time;

 

Spread the love