標籤:hash getc time() err select mem ice tco extends
dbutils提供的handler轉換不能滿足實際業務開發的需求。比如枚舉轉int,時間類型LocalDateTime,實體物件的屬性名稱與欄位未能相對應。
mysql表member結構欄位: id、member_name、sex、createTime
public class Member {
private long id;
private String memberName;
private Sex sex;
private LocalDateTime createTime;
}
枚舉Sex 時間LocalDateTime沒有預設提供,需要轉換。資料的轉換需要實現ColumnHandler介面。此介面提供二個簡單方法:1、類型是否匹配public boolean match(Class<?> propType);
2、轉換資料 public Object apply(ResultSet rs, int columnIndex)。
一、定義二個類型轉換handler
public class LocalDateTimeHandler implements ColumnHandler {
@Override
public boolean match(Class<?> propType) {
return propType.equals(LocalDateTime.class);
}
@Override
public Object apply(ResultSet rs, int columnIndex) throws SQLException {
if (rs.getTimestamp(columnIndex) != null) {
return rs.getTimestamp(columnIndex).toLocalDateTime();
}
return null;
}
}
public class SexHandler implements ColumnHandler {
@Override
public boolean match(Class<?> propType) {
return propType.equals(Sex.class);
}
@Override
public Object apply(ResultSet rs, int columnIndex) throws SQLException {
for (Sex sex : Sex.values()){
if (sex.getIndex() == rs.getInt(columnIndex)){
return sex;
}
}
return null;
}
}
public enum Sex {
male(1,"男"),
female(0,"女")
;
private int index;
private String description;
Sex(int index, String description){
this.index = index;
this.description = description;
}
public int getIndex() {
return index;
}
public String getDescription() {
return description;
}
}
二、重構BeanProcessor
public class MyBeanProcessor extends BeanProcessor {
private static ServiceLoader<ColumnHandler> columnHandlers = ServiceLoader.load(ColumnHandler.class);
private static List<ColumnHandler> customList = new ArrayList<>();
static {
customList.add(new LocalDateTimeHandler());
customList.add(new SexHandler());
}
public MyBeanProcessor(Map<String, String> columnToPropertyMap){
super(columnToPropertyMap);
}
@Override
protected Object processColumn(ResultSet rs, int index, Class<?> propType)
throws SQLException {
Object retval = rs.getObject(index);
if ( !propType.isPrimitive() && retval == null ) {
return null;
}
for (ColumnHandler handler : columnHandlers) {
if (handler.match(propType)) {
retval = handler.apply(rs, index);
break;
}
}
for (ColumnHandler handler : customList){
if (handler.match(propType)){
retval = handler.apply(rs, index);
break;
}
}
return retval;
}
}
三、傳自訂參數轉換資料
@Test
public void customQuery() throws SQLException {
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from member";
Map<String, String> map = new HashMap();
map.put("member_name","memberName");
MyBeanProcessor bean = new MyBeanProcessor(map);
RowProcessor convert = new BasicRowProcessor(bean);
BeanListHandler<Member> handler = new BeanListHandler(Member.class,convert);
List<Member> list = queryRunner.query(getConn(),sql, handler);
System.out.println(JSON.toJSONString(list));
}
JDBC開源架構:DBUtils自訂業務類型相關轉換器