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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With