本文介绍了有没有一种将PostgreSQL hstore转换为JPA 2.1 DataType的优雅而常用的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JPA 2.1 Converter 将PostgreSQL hstore 转换为 Map< String,串GT;
但是我没有找到适用于EclipseLink和Hibernate等不同JPA提供程序的通用方法。所以我需要为每个JPA提供程序编写不同的转换器。



以下是EclipseLink和Hibernate使用不同转换器的示例。



对于不同的JPA提供者,是否有一种通用的方法? PostgreSQL JDBC驱动程序提供了一个实用程序类与/从字符串 byte []

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

@Converter
public class MyHStoreConverter实现了AttributeConverter< Map< String,String>,String> {
@Override
public String convertToDatabaseColumn(Map< String,String>属性){
return HStoreConverter.toString(attribute);
}

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






$ b然后,使用它与JPA 注释在你的实体中:

  @Entity 
public class MyEntity {
@Convert(converter = MyHStoreConverter.class )
私人地图< String,String> hstoreAttribute;
}

这是一个仅使用JPA标准的实现,因此应该是JPA提供者不可知的。但是,使用 Converter 映射到通用 Map<> 早已被Hibernate bug ,但已在Hibernate 5.0.0和4.3.11中修复。 HHH- p>

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.

这篇关于有没有一种将PostgreSQL hstore转换为JPA 2.1 DataType的优雅而常用的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 03:18