PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Come lavorare con PGpoint per la geolocalizzazione usando PostgreSQL?

Non c'è modo di salvare/aggiornare/ottenere/ Oggetto PGpoint direttamente, quindi devi creare il tuo tipo utente per supportare PGpoint per convertirlo, prima che questo venga salvato, UserType è una classe di Hibernate che permette di creare un tipo personalizzato per convertirlo prima di salvarlo sul database. Ecco il codice che devi implementare:

Primo: Necessità di creare una classe che implementi UserType :

public class PGPointType implements UserType {
    @Override
    public int[] sqlTypes() {
        return new int[]
                {
                        Types.VARCHAR
                };
    }

    @SuppressWarnings("rawtypes")
    @Override
    public Class<PGpoint> returnedClass() {
        return PGpoint.class;
    }

    @Override
    public boolean equals(Object obj, Object obj1) {
        return ObjectUtils.equals(obj, obj1);
    }

    @Override
    public int hashCode(Object obj) {
        return obj.hashCode();
    }

    @Override
    public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws SQLException {
        if (names.length == 1) {
            if (resultSet.wasNull() || resultSet.getObject(names[0]) == null) {
                return null;
            } else {
                return new PGpoint(resultSet.getObject(names[0]).toString());
            }
        }
        return null;
    }


    @Override
    public void nullSafeSet(PreparedStatement statement, Object value, int index, SharedSessionContractImplementor sharedSessionContractImplementor) throws SQLException {
        if (value == null) {
            statement.setNull(index, Types.OTHER);
        } else {
            statement.setObject(index, value, Types.OTHER);
        }
    }

    @Override
    public Object deepCopy(Object obj) {
        return obj;
    }

    @Override
    public boolean isMutable() {
        return Boolean.FALSE;
    }

    @Override
    public Serializable disassemble(Object obj) {
        return (Serializable) obj;
    }

    @Override
    public Object assemble(Serializable serializable, Object obj) {
        return serializable;
    }

    @Override
    public Object replace(Object obj, Object obj1, Object obj2) {
        return obj;
    }

}

Secondo: Necessità di aggiungere sull'intestazione dell'entità l'annotazione @TypeDef, aggiungere un nome e il PGPointType che l'hai creato e su qualche intestazione di campo di tipo PGpoint, aggiungere l'annotazione @Type con il nome che l'hai creato :

  @TypeDef(name = "type", typeClass = PGPointType.class)
  @Entity
  public class Entity {

       @Type(type = "type")
       private PGpoint pgPoint;

       // Getters and setters 

  }    

Cordiali saluti.