Skip to content

Commit

Permalink
Merge pull request #3 from ed-pilots-network/string-double-map-typeha…
Browse files Browse the repository at this point in the history
…ndler

add-string-double-map-typehandler
  • Loading branch information
Daniel-J-Mason authored Oct 26, 2023
2 parents 02a5099 + 5e895fe commit a0faa83
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Map<String, Double>> {

@Override
public void setNonNullParameter(PreparedStatement ps, int i, Map<String, Double> parameter, JdbcType jdbcType) throws SQLException {
PGobject pGobject = new PGobject();
pGobject.setType("hstore");
pGobject.setValue(HStoreConverter.toString(parameter));
ps.setObject(i, pGobject);
}

@Override
public Map<String, Double> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return readMap(rs.getString(columnName));
}

@Override
public Map<String, Double> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return readMap(rs.getString(columnIndex));
}

@Override
public Map<String, Double> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return readMap(cs.getString(columnIndex));
}

private Map<String, Double> readMap(String hstring) throws SQLException {
if (hstring != null) {
Map<String, Double> map = new LinkedHashMap<>();
Map<String, String> rawMap = HStoreConverter.fromString(hstring);
for (Map.Entry<String, String> entry : rawMap.entrySet()) {
map.put(entry.getKey(), Double.parseDouble(entry.getValue())); // convert from <String, String> to <String,Double>
}

return map;
}
return null;
}
}

0 comments on commit a0faa83

Please sign in to comment.