diff --git a/build.gradle b/build.gradle index 01d2470..3b868a0 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,7 @@ plugins { } group = 'io.edpn.backend' -version = '0.0.1-SNAPSHOT' +version = '0.0.2-SNAPSHOT' compileJava.options.encoding = 'UTF-8' repositories { diff --git a/src/main/java/io/edpn/backend/mybatisutil/StringDoubleMapTypeHandler.java b/src/main/java/io/edpn/backend/mybatisutil/StringDoubleMapTypeHandler.java new file mode 100644 index 0000000..eef62ad --- /dev/null +++ b/src/main/java/io/edpn/backend/mybatisutil/StringDoubleMapTypeHandler.java @@ -0,0 +1,57 @@ +package io.edpn.backend.mybatisutil; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; +import org.apache.ibatis.type.MappedJdbcTypes; +import org.apache.ibatis.type.MappedTypes; +import org.postgresql.util.HStoreConverter; +import org.postgresql.util.PGobject; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.LinkedHashMap; +import java.util.Map; + +@MappedTypes(Map.class) +@MappedJdbcTypes(JdbcType.OTHER) +public class StringDoubleMapTypeHandler extends BaseTypeHandler> { + + @Override + public void setNonNullParameter(PreparedStatement ps, int i, Map parameter, JdbcType jdbcType) throws SQLException { + PGobject pGobject = new PGobject(); + pGobject.setType("hstore"); + pGobject.setValue(HStoreConverter.toString(parameter)); + ps.setObject(i, pGobject); + } + + @Override + public Map getNullableResult(ResultSet rs, String columnName) throws SQLException { + return readMap(rs.getString(columnName)); + } + + @Override + public Map getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return readMap(rs.getString(columnIndex)); + } + + @Override + public Map getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return readMap(cs.getString(columnIndex)); + } + + private Map readMap(String hstring) throws SQLException { + if (hstring != null) { + Map map = new LinkedHashMap<>(); + Map rawMap = HStoreConverter.fromString(hstring); + for (Map.Entry entry : rawMap.entrySet()) { + map.put(entry.getKey(), Double.parseDouble(entry.getValue())); // convert from to + } + + return map; + } + return null; + } +} +