2017년 11월 16일 목요일

mybatis hashmap으로 값 가져오기.

한개의 필드의 값을 hashmap으로 가져오려고 한다.

DB 내용
key1:value1,key2:value2,key3:value3

List<String> 으로 가져온 것과 마찬가지로 typeHandler를 사용하여 처리하였다.

 

DTO
HashMap<String, Object> extraProperties;


public HashMap<String, Object> getExtraProperties() {
return extraProperties;
}

public void setExtraProperties(HashMap<String, Object> extraProperties) {
this.extraProperties = extraProperties;
}

 

mybatis resultmap
<result property="extraProperties" column="extraProperties" typeHandler="com.my.handler.StringSplitMapTypeHandler" />

 

handler
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import com.my.util.CommonUtil;

public class StringSplitMapTypeHandler implements TypeHandler<HashMap<String,Object>> {

@Override
public void setParameter(PreparedStatement ps, int i, HashMap<String,Object> parameter, JdbcType jdbcType) throws SQLException {
if (parameter != null) {
ps.setString(i, parameter.toString());
}
}

@Override
public HashMap<String,Object> getResult(ResultSet rs, String columnName) throws SQLException {
String columnValueStr = rs.getString(columnName);
return CommonUtil.getStringSplitHashMap(columnValueStr, ",", ":");

}

@Override
public HashMap<String,Object> getResult(ResultSet rs, int columnIndex) throws SQLException {
String columnValueStr = rs.getString(columnIndex);
return CommonUtil.getStringSplitHashMap(columnValueStr, ",", ":");
}

@Override
public HashMap<String,Object> getResult(CallableStatement cs, int columnIndex) throws SQLException {
String columnValueStr = cs.getString(columnIndex);
return CommonUtil.getStringSplitHashMap(columnValueStr, ",", ":");
}
}

 

getStringSplitHashMap 코드
	public static HashMap<String,Object> getStringSplitHashMap(String targetStr, String fieldSeparator, String mapSeparator){
if (targetStr == null) return null;
String[] fields = targetStr.split(fieldSeparator);
HashMap<String,Object> returnData = new HashMap<String,Object>();
for(String str : fields){
String[] splitStr = str.split(mapSeparator);
if(splitStr.length < 2) continue;
String key = splitStr[0];
String value = splitStr[1];
returnData.put(key, value);
}
return returnData;
}

댓글 없음:

댓글 쓰기