Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails (Hibernate) Mapping of java.time.ZoneId to Database

Is there any way how to support persistent mapping of java.time.ZoneId to string in Hibernate 5.1.1. It saves the ZoneId in binary form right now.

I've just upgraded to Grails 3.2.1 which has Hibernate 5.1.1. Saving of java.time.Instant for example works fine however java.time.ZoneId is stored only in binary form.

I think there is no support from Hibernate. So how can I code my own mapping. I've tried to use Jadira Framework but it is not possible as there are some conflicts (exceptions) when starting the grails app.

like image 948
kuceram Avatar asked Oct 24 '16 08:10

kuceram


Video Answer


2 Answers

You can use a custom attribute converter as defined by JPA 2.1. Declare the converter class like so:

@Converter
public static class ZoneIdConverter implements AttributeConverter<ZoneId, String> {

    @Override
    public String convertToDatabaseColumn(ZoneId attribute) {
        return attribute.getId();
    }

    @Override
    public ZoneId convertToEntityAttribute(String dbData) {
        return ZoneId.of( dbData );
    }
}

And then refer to it from the entity attribute of type ZoneId:

@Convert(converter = ZoneIdConverter.class)
private ZoneId zoneId;

The converter will automatically be invoked when persisting/loading the zoneId attribute.

like image 161
Gunnar Avatar answered Oct 04 '22 22:10

Gunnar


You can use Hibernate types library and then just write

@Column
private ZoneId zoneId;

in your entity classes. You have to mark the entity class with this annotation:

@TypeDef(typeClass = ZoneIdType.class, defaultForType = ZoneId.class)
like image 27
izogfif Avatar answered Oct 04 '22 23:10

izogfif