how to store PostgreSQL jsonb using SpringBoot + JPA?

后端 未结 4 1734
不知归路
不知归路 2021-02-01 10:23

I\'m working on a migration software that will consume unknown data from REST services.

I already think about use MongoDB but I decide to not use it and use PostgreSQL.<

4条回答
  •  Happy的楠姐
    2021-02-01 10:58

    For this case, I use the above tailored converter class, you are free to add it in your library. It is working with the EclipseLink JPA Provider.

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.apache.log4j.Logger;
    import org.postgresql.util.PGobject;
    
    import javax.persistence.AttributeConverter;
    import javax.persistence.Converter;
    import java.io.IOException;
    import java.sql.SQLException;
    import java.util.Map;
    
    @Converter
    public final class PgJsonbToMapConverter implements AttributeConverter, PGobject> {
    
        private static final Logger LOGGER = Logger.getLogger(PgJsonbToMapConverter.class);
        private static final ObjectMapper MAPPER = new ObjectMapper();
    
        @Override
        public PGobject convertToDatabaseColumn(Map map) {
            PGobject po = new PGobject();
            po.setType("jsonb");
    
            try {
                po.setValue(map == null ? null : MAPPER.writeValueAsString(map));
            } catch (SQLException | JsonProcessingException ex) {
                LOGGER.error("Cannot convert JsonObject to PGobject.");
                throw new IllegalStateException(ex);
            }
            return po;
        }
    
        @Override
        public Map convertToEntityAttribute(PGobject dbData) {
            if (dbData == null || dbData.getValue() == null) {
                return null;
            }
            try {
                return MAPPER.readValue(dbData.getValue(), new TypeReference>() {
                });
            } catch (IOException ex) {
                LOGGER.error("Cannot convert JsonObject to PGobject.");
                return null;
            }
        }
    
    }
    

    Usage example, for an entity named Customer.

    @Entity
    @Table(schema = "web", name = "customer")
    public class Customer implements Serializable {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;
    
        @Convert(converter = PgJsonbToMapConverter.class)
        private Map info;
    
        public Customer() {
            this.id = null;
            this.info = null;
        }
    
        // Getters and setter omitted.
    

提交回复
热议问题