上一篇文章为大家介绍了如何使用反射解析领域模型的属性信息并缓存,本节将介绍如何自动封装JDBC的结果集ResultSet到实体对象中,这里正好使用到缓存的领域模型。
我们先理一下思路:
- 怎样正确的调用如rs.getString("name")、rs.getLong("size")得到想要的数据,这些数据如何正确的调用实体的set方法设值,这里rs中获取的值必须是实体中属性的类型。
- PreparedStatement如何获取实体属性值设置到对应SQL参数中,如insert into tableName(id, name) values(?, ?)。我们知道PreparedStatement替换占位符设值的方式为:ps.setInt(i, parameter),ps.setString(i, parameter)等
- 如果解决了以上两个问题,封装ResultSet结果集到实体对象中可谓轻而易举。
我们采用为每个Java属性(对应数据库表字段类型)的提供一个映射器
全局提供一个映射器的注册服务,需要获取对应的映射器的时候直接从注册服务中获取即可。
映射器接口定义如下:
package com.applet.sql.type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by Jackie Liu on 2017/9/25.
*/
public interface TypeHandler {
void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
T getResult(ResultSet rs, String columnName) throws SQLException;
T getResult(ResultSet rs, int columnIndex) throws SQLException;
T getResult(CallableStatement cs, int columnIndex) throws SQLException;
Class getClazz();
}
使用模板方法为映射器提供公共的行为,变化的部分让子类实现:
package com.applet.sql.type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by Jackie Liu on 2017/9/25.
*/
public abstract class BaseTypeHandler implements TypeHandler {
@Override
public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
if (parameter == null) {
if (jdbcType == null) {
throw new RuntimeException("JDBC requires that the JdbcType must be specified for all nullable parameters.");
}
try {
ps.setNull(i, jdbcType.TYPE_CODE);
} catch (SQLException e) {
throw new RuntimeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " +
"Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " +
"Cause: " + e, e);
}
} else {
try {
setNonNullParameter(ps, i, parameter, jdbcType);
} catch (Exception e) {
throw new RuntimeException("Error setting non null for parameter #" + i + " with JdbcType " + jdbcType + " . " +
"Try setting a different JdbcType for this parameter or a different configuration property. " +
"Cause: " + e, e);
}
}
}
@Override
public T getResult(ResultSet rs, String columnName) throws SQLException {
T result;
try {
result = getNullableResult(rs, columnName);
} catch (Exception e) {
throw new RuntimeException("Error attempting to get column '" + columnName + "' from result set. Cause: " + e, e);
}
if (rs.wasNull()) {
return null;
} else {
return result;
}
}
@Override
public T getResult(ResultSet rs, int columnIndex) throws SQLException {
T result;
try {
result = getNullableResult(rs, columnIndex);
} catch (Exception e) {
throw new RuntimeException("Error attempting to get column #" + columnIndex+ " from result set. Cause: " + e, e);
}
if (rs.wasNull()) {
return null;
} else {
return result;
}
}
@Override
public T getResult(CallableStatement cs, int columnIndex) throws SQLException {
T result;
try {
result = getNullableResult(cs, columnIndex);
} catch (Exception e) {
throw new RuntimeException("Error attempting to get column #" + columnIndex+ " from callable statement. Cause: " + e, e);
}
if (cs.wasNull()) {
return null;
} else {
return result;
}
}
public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException;
public abstract T getNullableResult(ResultSet rs, int columnIndex) throws SQLException;
public abstract T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException;
}
每个子类实现方式如下(这里提供一个,其他的各位亲们可自己扩展或者给我留言):
package com.applet.sql.type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by Jackie Liu on 2017/9/25.
*/
public class IntegerTypeHandler extends BaseTypeHandler {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Integer parameter, JdbcType jdbcType)
throws SQLException {
ps.setInt(i, parameter);
}
@Override
public Integer getNullableResult(ResultSet rs, String columnName)
throws SQLException {
return rs.getInt(columnName);
}
@Override
public Integer getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
return rs.getInt(columnIndex);
}
@Override
public Integer getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return cs.getInt(columnIndex);
}
@Override
public Class getClazz() {
return Integer.class;
}
}
全局的注册服务如下:
package com.applet.sql.type;
import com.alibaba.druid.support.logging.Resources;
import com.applet.sql.record.JSONB;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by Jackie Liu on 2017/9/25.
*/
@SuppressWarnings({"ALL", "AlibabaClassMustHaveAuthor"})
public class TypeHandlerRegistry {
// EnumMap,保存JDBC内部提供的枚举JdbcType类型和对应的TypeHandler
private final Map> JDBC_TYPE_HANDLER_MAP = new EnumMap>(JdbcType.class);
// Type:javaType的Class类型(Type是Class的接口),value是一个Map集合(比如String,可能对应数据库的clob、char、varchar等,所以是一对多关系)
private final Map>> TYPE_HANDLER_MAP = new ConcurrentHashMap>>();
// 处理Object类型(运行时,会尝试进行向下类型转换找到合适的TypeHandler,如果依然失败,最后选择ObjectTypeHandler)
private final TypeHandler
有了这些我们就可以轻松封装结果集到对象了,默认的jdbcTemplate rowMapper如下:
package com.applet.sql.mapper;
import com.applet.sql.builder.SelectBuilder;
import com.applet.sql.record.DomainModelContext;
import com.applet.sql.record.DomainModelAnalysis;
import com.applet.sql.record.TableColumn;
import com.applet.sql.type.JdbcType;
import com.applet.sql.type.TypeHandler;
import com.applet.sql.type.TypeHandlerRegistry;
import com.applet.utils.SpringContextHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.ReflectionUtils;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/**
* 默认的ORM方式
*
* @param
* @author Jackie Liu
*/
public class DefaultRowMapper implements RowMapper {
private DomainModelAnalysis domainModelAnalysis;
public DefaultRowMapper(DomainModelAnalysis domainModelAnalysis) {
this.domainModelAnalysis = domainModelAnalysis;
}
public DefaultRowMapper(Class cls) {
DomainModelContext commonModelContext = SpringContextHelper.getBean(DomainModelContext.class);
domainModelAnalysis = commonModelContext.getDomainModelAnalysis(cls);
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int count = metaData.getColumnCount();
T t = (T) BeanUtils.instantiate(domainModelAnalysis.getClazz());
for (int i = 1; i <= count; i++) {
String colName = metaData.getColumnLabel(i).toUpperCase();
TableColumn tableColumn = domainModelAnalysis.getTableColumnByColumnName(colName);
if (tableColumn == null) {
extendColumnRow(colName, t, metaData, i, rs);
continue;
}
int columnType = metaData.getColumnType(i);
TypeHandler typeHandler = getTypeHandler(columnType, tableColumn.getJavaType());
ReflectionUtils.invokeMethod(tableColumn.getFieldSetMethod(), t, typeHandler.getResult(rs, i));
}
return t;
}
private boolean extendColumnRow(String colName, T t, ResultSetMetaData metaData, int index, ResultSet rs) throws SQLException {
SelectBuilder.Column column = SelectBuilder.getExtendColumn(colName);
if (column == null) {
return false;
}
Object manyToOne = ReflectionUtils.invokeMethod(column.getGetModelMethod(), t);
if (manyToOne == null) {
manyToOne = BeanUtils.instantiate(column.getManyToOneClass());
ReflectionUtils.invokeMethod(column.getSetModelMethod(), t, manyToOne);
}
TableColumn tableColumn = column.getManyToOneTableColumn();
int columnType = metaData.getColumnType(index);
TypeHandler typeHandler = getTypeHandler(columnType, tableColumn.getJavaType());
ReflectionUtils.invokeMethod(tableColumn.getFieldSetMethod(), manyToOne, typeHandler.getResult(rs, index));
return true;
}
private TypeHandler getTypeHandler(int columnType, Class> javaType) {
TypeHandlerRegistry typeHandlerRegistry = DomainModelContext.getTypeHandlerRegistry();
TypeHandler typeHandler = typeHandlerRegistry.getTypeHandler(JdbcType.forCode(columnType));
if (typeHandler != null && javaType.getName().equals(typeHandler.getClazz().getName())) {
return typeHandler;
}
typeHandler = typeHandlerRegistry.getTypeHandler(javaType);
return typeHandler;
}
}
下一节将为大家介绍如何封装不同数据库的分页语句,只需要配置一下即可,应用层无需实现分页逻辑。