3 基于Spring JDBC实现关键功能 3.1 ClassMappings本文节选自《Spring 5核心原理》
ClassMappings主要定义基础的映射类型,代码如下:
package com.tom.orm.framework;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ClassMappings {
private ClassMappings(){}
static final Set> SUPPORTED_SQL_OBJECTS = new HashSet>();
static {
//只要这里写了,默认支持自动类型转换
Class>[] classes = {
boolean.class, Boolean.class,
short.class, Short.class,
int.class, Integer.class,
long.class, Long.class,
float.class, Float.class,
double.class, Double.class,
String.class,
Date.class,
Timestamp.class,
BigDecimal.class
};
SUPPORTED_SQL_OBJECTS.addAll(Arrays.asList(classes));
}
static boolean isSupportedSQLObject(Class> clazz) {
return clazz.isEnum() || SUPPORTED_SQL_OBJECTS.contains(clazz);
}
public static Map findPublicGetters(Class> clazz) {
Map map = new HashMap();
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (Modifier.isStatic(method.getModifiers()))
continue;
if (method.getParameterTypes().length != 0)
continue;
if (method.getName().equals("getClass"))
continue;
Class> returnType = method.getReturnType();
if (void.class.equals(returnType))
continue;
if(!isSupportedSQLObject(returnType)){
continue;
}
if ((returnType.equals(boolean.class)
|| returnType.equals(Boolean.class))
&& method.getName().startsWith("is")
&& method.getName().length() > 2) {
map.put(getGetterName(method), method);
continue;
}
if ( ! method.getName().startsWith("get"))
continue;
if (method.getName().length() < 4)
continue;
map.put(getGetterName(method), method);
}
return map;
}
public static Field[] findFields(Class> clazz){
return clazz.getDeclaredFields();
}
public static Map findPublicSetters(Class> clazz) {
Map map = new HashMap();
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (Modifier.isStatic(method.getModifiers()))
continue;
if ( ! void.class.equals(method.getReturnType()))
continue;
if (method.getParameterTypes().length != 1)
continue;
if ( ! method.getName().startsWith("set"))
continue;
if (method.getName().length() < 4)
continue;
if(!isSupportedSQLObject(method.getParameterTypes()[0])){
continue;
}
map.put(getSetterName(method), method);
}
return map;
}
public static String getGetterName(Method getter) {
String name = getter.getName();
if (name.startsWith("is"))
name = name.substring(2);
else
name = name.substring(3);
return Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
private static String getSetterName(Method setter) {
String name = setter.getName().substring(3);
return Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
}
3.2 EntityOperation
EntityOperation主要实现数据库表结构和对象类结构的映射关系,代码如下:
package com.tom.orm.framework; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.ResultSetmetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.log4j.Logger; import org.springframework.jdbc.core.RowMapper; import javax.core.common.utils.StringUtils; public class EntityOperation3.3 QueryRuleSqlBuilder{ private Logger log = Logger.getLogger(EntityOperation.class); public Class entityClass = null; // 泛型实体Class对象 public final Map mappings; public final RowMapper rowMapper; public final String tableName; public String allColumn = "*"; public Field pkField; public EntityOperation(Class clazz,String pk) throws Exception{ if(!clazz.isAnnotationPresent(Entity.class)){ throw new Exception("在" + clazz.getName() + "中没有找到Entity注解,不能做ORM映射"); } this.entityClass = clazz; Table table = entityClass.getAnnotation(Table.class); if (table != null) { this.tableName = table.name(); } else { this.tableName = entityClass.getSimpleName(); } Map getters = ClassMappings.findPublicGetters(entityClass); Map setters = ClassMappings.findPublicSetters(entityClass); Field[] fields = ClassMappings.findFields(entityClass); fillPkFieldAndAllColumn(pk,fields); this.mappings = getPropertyMappings(getters, setters, fields); this.allColumn = this.mappings.keySet().toString().replace("[", "").replace("]",""). replaceAll(" ",""); this.rowMapper = createRowMapper(); } Map getPropertyMappings(Map getters, Map setters, Field[] fields) { Map mappings = new HashMap (); String name; for (Field field : fields) { if (field.isAnnotationPresent(Transient.class)) continue; name = field.getName(); if(name.startsWith("is")){ name = name.substring(2); } name = Character.toLowerCase(name.charAt(0)) + name.substring(1); Method setter = setters.get(name); Method getter = getters.get(name); if (setter == null || getter == null){ continue; } Column column = field.getAnnotation(Column.class); if (column == null) { mappings.put(field.getName(), new PropertyMapping(getter, setter, field)); } else { mappings.put(column.name(), new PropertyMapping(getter, setter, field)); } } return mappings; } RowMapper createRowMapper() { return new RowMapper () { public T mapRow(ResultSet rs, int rowNum) throws SQLException { try { T t = entityClass.newInstance(); ResultSetmetaData meta = rs.getmetaData(); int columns = meta.getColumnCount(); String columnName; for (int i = 1; i <= columns; i++) { Object value = rs.getObject(i); columnName = meta.getColumnName(i); fillBeanFieldValue(t,columnName,value); } return t; }catch (Exception e) { throw new RuntimeException(e); } } }; } protected void fillBeanFieldValue(T t, String columnName, Object value) { if (value != null) { PropertyMapping pm = mappings.get(columnName); if (pm != null) { try { pm.set(t, value); } catch (Exception e) { e.printStackTrace(); } } } } private void fillPkFieldAndAllColumn(String pk, Field[] fields) { //设定主键 try { if(!StringUtils.isEmpty(pk)){ pkField = entityClass.getDeclaredField(pk); pkField.setAccessible(true); } } catch (Exception e) { log.debug("没找到主键列,主键列名必须与属性名相同"); } for (int i = 0 ; i < fields.length ;i ++) { Field f = fields[i]; if(StringUtils.isEmpty(pk)){ Id id = f.getAnnotation(Id.class); if(id != null){ pkField = f; break; } } } } public T parse(ResultSet rs) { T t = null; if (null == rs) { return null; } Object value = null; try { t = (T) entityClass.newInstance(); for (String columnName : mappings.keySet()) { try { value = rs.getObject(columnName); } catch (Exception e) { e.printStackTrace(); } fillBeanFieldValue(t,columnName,value); } } catch (Exception ex) { ex.printStackTrace(); } return t; } public Map parse(T t) { Map _map = new TreeMap (); try { for (String columnName : mappings.keySet()) { Object value = mappings.get(columnName).getter.invoke(t); if (value == null) continue; _map.put(columnName, value); } } catch (Exception e) { e.printStackTrace(); } return _map; } public void println(T t) { try { for (String columnName : mappings.keySet()) { Object value = mappings.get(columnName).getter.invoke(t); if (value == null) continue; System.out.println(columnName + " = " + value); } } catch (Exception e) { e.printStackTrace(); } } } class PropertyMapping { final boolean insertable; final boolean updatable; final String columnName; final boolean id; final Method getter; final Method setter; final Class enumClass; final String fieldName; public PropertyMapping(Method getter, Method setter, Field field) { this.getter = getter; this.setter = setter; this.enumClass = getter.getReturnType().isEnum() ? getter.getReturnType() : null; Column column = field.getAnnotation(Column.class); this.insertable = column == null || column.insertable(); this.updatable = column == null || column.updatable(); this.columnName = column == null ? ClassMappings.getGetterName(getter) : ("".equals(column.name()) ? ClassMappings.getGetterName(getter) : column.name()); this.id = field.isAnnotationPresent(Id.class); this.fieldName = field.getName(); } @SuppressWarnings("unchecked") Object get(Object target) throws Exception { Object r = getter.invoke(target); return enumClass == null ? r : Enum.valueOf(enumClass, (String) r); } @SuppressWarnings("unchecked") void set(Object target, Object value) throws Exception { if (enumClass != null && value != null) { value = Enum.valueOf(enumClass, (String) value); } //BeanUtils.setProperty(target, fieldName, value); try { if(value != null){ setter.invoke(target, setter.getParameterTypes()[0].cast(value)); } } catch (Exception e) { e.printStackTrace(); System.err.println(fieldName + "--" + value); } } }
QueryRuleSqlBuilder根据用户构建好的QueryRule来自动生成SQL语句,代码如下:
package com.tom.orm.framework;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.ArrayUtils;
import com.tom.orm.framework.QueryRule.Rule;
import javax.core.common.utils.StringUtils;
public class QueryRuleSqlBuilder {
private int CURR_INDEX = 0; //记录参数所在的位置
private List properties; //保存列名列表
private List
3.4 baseDaoSupport
baseDaoSupport主要是对JdbcTemplate的包装,下面讲一下其重要代码,请“小伙伴们” 关 注 公 众 号 『 Tom弹架构 』,回复 " Spring " 可下载全部源代码。先看全局定义:
package com.tom.orm.framework; ... public abstract class baseDaoSupportimplements baseDao { private Logger log = Logger.getLogger(baseDaoSupport.class); private String tableName = ""; private JdbcTemplate jdbcTemplateWrite; private JdbcTemplate jdbcTemplateReadOnly; private DataSource dataSourceReadOnly; private DataSource dataSourceWrite; private EntityOperation op; @SuppressWarnings("unchecked") protected baseDaoSupport(){ try{ Class entityClass = GenericsUtils.getSuperClassGenricType(getClass(), 0); op = new EntityOperation (entityClass,this.getPKColumn()); this.setTableName(op.tableName); }catch(Exception e){ e.printStackTrace(); } } protected String getTableName() { return tableName; } protected DataSource getDataSourceReadOnly() { return dataSourceReadOnly; } protected DataSource getDataSourceWrite() { return dataSourceWrite; } protected void setTableName(String tableName) { if(StringUtils.isEmpty(tableName)){ this.tableName = op.tableName; }else{ this.tableName = tableName; } } protected void setDataSourceWrite(DataSource dataSourceWrite) { this.dataSourceWrite = dataSourceWrite; jdbcTemplateWrite = new JdbcTemplate(dataSourceWrite); } protected void setDataSourceReadOnly(DataSource dataSourceReadOnly) { this.dataSourceReadonly = dataSourceReadOnly; jdbcTemplateReadonly = new JdbcTemplate(dataSourceReadOnly); } private JdbcTemplate jdbcTemplateReadOnly() { return this.jdbcTemplateReadOnly; } private JdbcTemplate jdbcTemplateWrite() { return this.jdbcTemplateWrite; } protected void restoreTableName(){ this.setTableName(op.tableName); } protected abstract String getPKColumn(); protected abstract void setDataSource(DataSource dataSource); //此处有省略 }
为了照顾程序员的一般使用习惯,查询方法的前缀命名主要有select、get、load,兼顾Hibernate和MyBatis的命名风格。
public Listselect(QueryRule queryRule) throws Exception{ QueryRuleSqlBuilder bulider = new QueryRuleSqlBuilder(queryRule); String ws = removeFirstAnd(bulider.getWhereSql()); String whereSql = ("".equals(ws) ? ws : (" where " + ws)); String sql = "select " + op.allColumn + " from " + getTableName() + whereSql; Object [] values = bulider.getValues(); String orderSql = bulider.getOrderSql(); orderSql = (StringUtils.isEmpty(orderSql) ? " " : (" order by " + orderSql)); sql += orderSql; log.debug(sql); return (List ) this.jdbcTemplateReadOnly().query(sql, this.op.rowMapper, values); } ... public List
插入方法,均以insert开头:
public PK insertAndReturnId(T entity) throws Exception{
return (PK)this.doInsertRuturnKey(parse(entity));
}
public boolean insert(T entity) throws Exception{
return this.doInsert(parse(entity));
}
public int insertAll(List list) throws Exception {
int count = 0 ,len = list.size(),step = 50000;
Map pm = op.mappings;
int maxPage = (len % step == 0) ? (len / step) : (len / step + 1);
for (int i = 1; i <= maxPage; i ++) {
Page page = pagination(list, i, step);
String sql = "insert into " + getTableName() + "(" + op.allColumn + ") values ";// (" + valstr.toString() + ")";
StringBuffer valstr = new StringBuffer();
Object[] values = new Object[pm.size() * page.getRows().size()];
for (int j = 0; j < page.getRows().size(); j ++) {
if(j > 0 && j < page.getRows().size()){ valstr.append(","); }
valstr.append("(");
int k = 0;
for (PropertyMapping p : pm.values()) {
values[(j * pm.size()) + k] = p.getter.invoke(page.getRows().get(j));
if(k > 0 && k < pm.size()){ valstr.append(","); }
valstr.append("?");
k ++;
}
valstr.append(")");
}
int result = jdbcTemplateWrite().update(sql + valstr.toString(), values);
count += result;
}
return count;
}
private Serializable doInsertRuturnKey(Map params){
final List values = new ArrayList();
final String sql = makeSimpleInsertSql(getTableName(),params,values);
KeyHolder keyHolder = new GeneratedKeyHolder();
final JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSourceWrite());
try {
jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(
Connection con) throws SQLException {
PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < values.size(); i++) {
ps.setObject(i+1, values.get(i)==null?null:values.get(i));
}
return ps;
}
}, keyHolder);
} catch (DataAccessException e) {
log.error("error",e);
}
if (keyHolder == null) { return ""; }
Map keys = keyHolder.getKeys();
if (keys == null || keys.size() == 0 || keys.values().size() == 0) {
return "";
}
Object key = keys.values().toArray()[0];
if (key == null || !(key instanceof Serializable)) {
return "";
}
if (key instanceof Number) {
//Long k = (Long) key;
Class clazz = key.getClass();
// return clazz.cast(key);
return (clazz == int.class || clazz == Integer.class) ? ((Number) key).intValue() : ((Number)key).longValue();
} else if (key instanceof String) {
return (String) key;
} else {
return (Serializable) key;
}
}
private boolean doInsert(Map params) {
String sql = this.makeSimpleInsertSql(this.getTableName(), params);
int ret = this.jdbcTemplateWrite().update(sql, params.values().toArray());
return ret > 0;
}
删除方法,均以delete开头:
public boolean delete(T entity) throws Exception {
return this.doDelete(op.pkField.get(entity)) > 0;
}
public int deleteAll(List list) throws Exception {
String pkName = op.pkField.getName();
int count = 0 ,len = list.size(),step = 1000;
Map pm = op.mappings;
int maxPage = (len % step == 0) ? (len / step) : (len / step + 1);
for (int i = 1; i <= maxPage; i ++) {
StringBuffer valstr = new StringBuffer();
Page page = pagination(list, i, step);
Object[] values = new Object[page.getRows().size()];
for (int j = 0; j < page.getRows().size(); j ++) {
if(j > 0 && j < page.getRows().size()){ valstr.append(","); }
values[j] = pm.get(pkName).getter.invoke(page.getRows().get(j));
valstr.append("?");
}
String sql = "delete from " + getTableName() + " where " + pkName + " in (" + valstr.toString() + ")";
int result = jdbcTemplateWrite().update(sql, values);
count += result;
}
return count;
}
protected void deleteByPK(PK id) throws Exception {
this.doDelete(id);
}
private int doDelete(String tableName, String pkName, Object pkValue) {
StringBuffer sb = new StringBuffer();
sb.append("delete from ").append(tableName).append(" where ").append(pkName).append(" = ?");
int ret = this.jdbcTemplateWrite().update(sb.toString(), pkValue);
return ret;
}
修改方法,均以update开头:
public boolean update(T entity) throws Exception {
return this.doUpdate(op.pkField.get(entity), parse(entity)) > 0;
}
private int doUpdate(Object pkValue, Map params){
String sql = this.makeDefaultSimpleUpdateSql(pkValue, params);
params.put(this.getPKColumn(), pkValue);
int ret = this.jdbcTemplateWrite().update(sql, params.values().toArray());
return ret;
}
至此一个完整的ORM框架就横空出世。当然,还有很多优化的地方,请小伙伴可以继续完善。
关注微信公众号『 Tom弹架构 』回复“Spring”可获取完整源码。
本文为“Tom弹架构”原创,转载请注明出处。技术在于分享,我分享我快乐!
如果您有任何建议也可留言评论或私信,您的支持是我坚持创作的动力。关注微信公众号『 Tom弹架构 』可获取更多技术干货!
原创不易,坚持很酷,都看到这里了,小伙伴记得点赞、收藏、在看,一键三连加关注!如果你觉得内容太干,可以分享转发给朋友滋润滋润!



