Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a elegant and common way for converting PostgreSQL hstore to JPA 2.1 DataType?

I have used JPA 2.1 Converter to convert PostgreSQL hstore to Map<String, String>. But I didn't find a universal way for different JPA providers such as EclipseLink and Hibernate. So I need to write different Converters for each JPA provider.

The following is the example which uses different Converters for EclipseLink and Hibernate. https://github.com/phstudy/jpa-converter-sample

Is there an universal way for different JPA providers?

like image 660
study Avatar asked Mar 07 '14 05:03

study


1 Answers

The PostgreSQL JDBC driver provides a org.postgresql.util.HStoreConverter utility class with to/from String and byte[] conversion. You can use it to implement your own JPA 2.1 Converter:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Map;
import org.postgresql.util.HStoreConverter;

@Converter
public class MyHStoreConverter implements AttributeConverter<Map<String, String>, String> {
    @Override
    public String convertToDatabaseColumn(Map<String, String> attribute) {
        return HStoreConverter.toString(attribute);
    }

    @Override
    public Map<String, String> convertToEntityAttribute(String dbData) {
        return HStoreConverter.fromString(dbData);
    }
}

Then, use it with the JPA Convert annotation in your entity:

@Entity
public class MyEntity {
    @Convert(converter = MyHStoreConverter.class)
    private Map<String, String> hstoreAttribute;
}

This is an implementation using only JPA standards, so should be JPA-provider agnostic. However, using the Converter to map to a generic Map<> has earlier been blocked by the Hibernate bug HHH-8804, but that has been fixed in Hibernate 5.0.0 and 4.3.11.

like image 95
Adam Michalik Avatar answered Oct 12 '22 22:10

Adam Michalik