Commit b708b0ff authored by yanzg's avatar yanzg

对象之间的处理、复制

parent 6c23fd3b
......@@ -12,6 +12,7 @@
<modules>
<module>yzg-util-base</module>
<module>yzg-util-db</module>
<module>yzg-util-cloud</module>
</modules>
<properties>
......
......@@ -474,7 +474,7 @@ public class ByteHelper {
}
/**
* Convert char to byte
* convert char to byte
*
* @param c char
* @return byte
......
......@@ -124,7 +124,7 @@ public class StringHelper {
* @param from 对象
* @return 返回获取的值
*/
public static <T> T to(Class<T> cls, T from) {
public static <T> T to(Class<T> cls, Object from) {
String vName = cls.getName();
Object to = null;
if (cls.isEnum()) {
......@@ -148,8 +148,9 @@ public class StringHelper {
}
if (to != null) {
return (T) to;
} else {
return (T) from;
}
return from;
}
/**
......
package com.yanzuoguang.util.vo;
import java.util.HashMap;
/**
* 行映射
*/
public class MapRow extends HashMap<String, Object> {
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>yzg-util</artifactId>
<groupId>com.yanzuoguang</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>yzg-util-cloud</artifactId>
</project>
\ No newline at end of file
......@@ -3,13 +3,46 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>yzg-util</artifactId>
<groupId>com.yanzuoguang</groupId>
<artifactId>yzg-util</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>yzg-util-db</artifactId>
<dependencies>
<dependency>
<groupId>com.yanzuoguang</groupId>
<artifactId>yzg-util-base</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Spring依赖 -->
<!-- 1.Spring核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<!-- 2.Spring dao依赖 -->
<!-- spring-jdbc包括了一些如jdbcTemplate的工具类 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.yanzuoguang.db.db;
import com.yanzuoguang.util.vo.MapRow;
import java.util.List;
/**
* created by yanzu on 2017/5/30.
*/
public interface DbExecute {
/**
* 更新SQL语句的执行
* @param sql SQL语句
* @param paras 参数信息
* @return
*/
int update(String sql, Object... paras);
/**
* 查询数据,并返回集合
* @param cls 查询的结果的类型
* @param sql 需要查询的SQL语句
* @param paras 查询语句的参数
* @param <T> 返回的集合的类型
* @return 集合
*/
<T> List<T> query(Class<T> cls, String sql, Object... paras);
/**
* 查询数据,并返回集合
*
* @param sql 需要查询的SQL语句
* @param paras 查询语句的参数
* @return 集合
*/
List<MapRow> query(String sql, Object... paras);
/**
* 查询第一个单元格的信息
* @param sql SQL语句
* @param paras 参数信息
* @return 第一个单元格的数据
*/
Object queryCell(String sql, Object... paras);
}
package com.yanzuoguang.db.db.Impl;
import com.yanzuoguang.db.db.extend.ConfigDb;
import com.yanzuoguang.util.log.Log;
import com.yanzuoguang.util.obj.ObjectHelper;
import com.yanzuoguang.util.vo.MapRow;
import org.springframework.beans.*;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* 将数据映射为结果
* Created by yanzu on 2017/5/31.
*/
public class AllBeanRowMapper<T> implements RowMapper<T> {
/**
* 需要映射的Class
*/
private Class<T> mappedClass;
/**
* Mappings是否属于字段s
*/
private Map<String, Boolean> mappedIsFields;
/**
* 需要映射的字段
*/
private Map<String, Field> mappedFields;
/**
* 需要映射的属性
*/
private Map<String, PropertyDescriptor> mappedPropertys;
/**
* 是否属于映射方式
*/
private boolean isMapping = false;
/**
* 构造函数
*
* @param mappedClass
*/
public AllBeanRowMapper(Class<T> mappedClass) {
initialize(mappedClass);
}
/**
* 初始化元素之间的映射关系
*
* @param mappedClass the mapped class.
*/
protected void initialize(Class<T> mappedClass) {
this.mappedClass = mappedClass;
this.mappedFields = new HashMap<>();
this.mappedPropertys = new HashMap<>();
this.mappedIsFields = new HashMap<>();
if (ObjectHelper.isSub(MapRow.class, mappedClass) || ObjectHelper.isSub(Map.class, mappedClass)) {
isMapping = true;
} else {
Field[] fields = mappedClass.getFields();
for (Field item : fields) {
if (Modifier.isStatic(item.getModifiers())) {
continue;
}
String name = item.getName();
String underscoredName = underscoreName(name);
this.mappedFields.put(underscoredName, item);
this.mappedIsFields.put(underscoredName, true);
}
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
for (PropertyDescriptor item : pds) {
if (item.getWriteMethod() != null) {
String name = item.getName();
String underscoredName = underscoreName(name);
this.mappedPropertys.put(underscoredName, item);
this.mappedIsFields.put(underscoredName, false);
}
}
}
}
/**
* convert a name in camelCase to an underscored name in lower case.
* Any upper case letters are converted to lower case with a preceding underscore.
*
* @param name the string containing original name
* @return the converted name
*/
private String underscoreName(String name) {
if (!StringUtils.hasLength(name)) {
return "";
}
return name.toLowerCase().replace("_", "");
}
/**
* Extract the values for all columns in the current row.
* <p>Utilizes public setters and result setByType metadata.
*
* @see ResultSetMetaData
*/
public T mapRow(ResultSet rs, int rowNumber) throws SQLException, TypeMismatchException {
Assert.state(this.mappedClass != null, "Mapped class was not specified");
T mappedObject = BeanUtils.instantiate(this.mappedClass);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
initBeanWrapper(bw);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int index = 1; index <= columnCount; index++) {
String column = JdbcUtils.lookupColumnName(rsmd, index);
String underscoredName = underscoreName(column);
if (this.isMapping) {
Object value = JdbcUtils.getResultSetValue(rs, index);
((Map) mappedObject).put(column, value);
} else if (!this.mappedIsFields.containsKey(underscoredName)) {
continue;
} else if (!this.mappedIsFields.get(underscoredName)) {
PropertyDescriptor pd = this.mappedPropertys.get(underscoredName);
Class<?> type = pd.getPropertyType();
try {
Object value = JdbcUtils.getResultSetValue(rs, index, type);
if (ConfigDb.PrintMapper && rowNumber == 0) {
Log.info(AllBeanRowMapper.class, "Mapping column '%s' to property '%s' of type %s", column, pd.getName(), type);
}
try {
bw.setPropertyValue(pd.getName(), value);
} catch (TypeMismatchException e) {
if (value == null) {
Log.info(AllBeanRowMapper.class,
"Intercepted TypeMismatchException for row %d and column '%s' with " +
"value %s when setting property '%s' of type %s on object: %s",
rowNumber, column, value, pd.getName(), type, mappedObject);
} else {
throw e;
}
}
} catch (NotWritablePropertyException ex) {
throw new DataRetrievalFailureException("Unable to map column " + column + " to property " + pd.getName(), ex);
}
} else {
Field pd = this.mappedFields.get(underscoredName);
Class<?> type = pd.getType();
try {
Object value = JdbcUtils.getResultSetValue(rs, index, type);
// value = StringHelper.get(type,value);
if (ConfigDb.PrintMapper && rowNumber == 0) {
Log.info(AllBeanRowMapper.class, "Mapping column '%s' to property '%s' of type %s", column, pd.getName(), type);
}
try {
pd.set(mappedObject, value);
} catch (IllegalAccessException e) {
if (value == null) {
Log.info(AllBeanRowMapper.class,
"Intercepted TypeMismatchException for row %d and column '%s' with " +
"value %s when setting property '%s' of type %s on object: %s",
rowNumber, column, value, pd.getName(), type, mappedObject);
} else {
throw e;
}
}
} catch (IllegalAccessException ex) {
throw new DataRetrievalFailureException("Unable to map column " + column + " to field " + pd.getName(), ex);
}
}
}
return mappedObject;
}
/**
* Initialize the given BeanWrapper to be used for row mapping.
* To be called for each row.
* <p>The default implementation is empty. Can be overridden in subclasses.
*
* @param bw the BeanWrapper to initialize
*/
protected void initBeanWrapper(BeanWrapper bw) {
}
/**
* 缓存的处理类
*/
private static Map<Class, Object> Cache = new HashMap<Class, Object>();
/**
* 获取可以转化实体
*
* @param cls 类型
* @param <T> 泛型类型
* @return 可转换的实体
*/
public static <T extends Object> AllBeanRowMapper<T> getIntance(Class<T> cls) {
if (!Cache.containsKey(cls)) {
Cache.put(cls, new AllBeanRowMapper<T>(cls));
}
AllBeanRowMapper<T> ret = (AllBeanRowMapper<T>) Cache.get(cls);
return ret;
}
}
package com.yanzuoguang.db.db.Impl;
import com.yanzuoguang.db.db.DbExecute;
import com.yanzuoguang.util.vo.MapRow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* 数据库操作类
*/
@Component
public class DbExecuteImpl implements DbExecute {
@Autowired
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbc;
@Autowired
private DbPrintSql printSql;
/**
* 更新SQL语句的执行
*
* @param sql SQL语句
* @param paras 参数信息
* @return
*/
public int update(String sql, Object... paras) {
int row = 0;
try {
sql = this.handleParas(sql, paras);
row = jdbc.update(sql, paras);
return row;
} finally {
printSql.print(row, sql, paras);
}
}
/**
* 查询数据,并返回集合
*
* @param cls 查询的结果的类型
* @param sql 需要查询的SQL语句
* @param paras 查询语句的参数
* @param <T> 返回的集合的类型
* @return 集合
*/
public <T extends Object> List<T> query(Class<T> cls, String sql, Object... paras) {
int row = 0;
try {
sql = this.handleParas(sql, paras);
List<T> ret = jdbc.query(sql, paras, AllBeanRowMapper.getIntance(cls));
if (ret == null) {
ret = new ArrayList<T>();
}
row = ret.size();
return ret;
} finally {
printSql.print(row, sql, paras);
}
}
/**
* 查询数据,并返回集合
*
* @param sql 需要查询的SQL语句
* @param paras 查询语句的参数
* @return 集合
*/
public List<MapRow> query(String sql, Object... paras) {
return query(MapRow.class, sql, paras);
}
/**
* 查询第一个单元格的信息
*
* @param sql SQL语句
* @param paras 参数信息
* @return 第一个单元格的数据
*/
public Object queryCell(String sql, Object... paras) {
int row = 0;
try {
sql = this.handleParas(sql, paras);
SqlRowSet rowSet = jdbc.queryForRowSet(sql, paras);
while (rowSet.next()) {
row = 1;
return rowSet.getObject(1);
}
return null;
} finally {
printSql.print(row, sql, paras);
}
}
/**
* 处理SQL语句和参数值
*
* @param sql
* @param paras
* @return
*/
protected String handleParas(String sql, Object... paras) {
return sql.replaceAll("1\\s*?=\\s*?1\\s*?(?i)AND", "")
.replaceAll("(?i)WHERE\\s*?1\\s*?=\\s*?1", "");
}
}
package com.yanzuoguang.db.db.Impl;
import com.yanzuoguang.db.db.extend.ConfigDb;
import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log;
import org.springframework.stereotype.Component;
@Component
public class DbPrintSql {
/**
* 打印SQL语句
*
* @param sql SQL语句
* @param paras 参数
*/
public void print(int row, String sql, Object... paras) {
// 日志表忽略打印
if (!ConfigDb.PrintSql) {
return;
}
if (!StringHelper.isEmpty(ConfigDb.PrintSqlFilter)) {
if (sql.matches(ConfigDb.PrintSqlFilter)) {
return;
}
}
// 进行SQL语句参数替换,后面增加一个空格,方便后续用正则表达式进行替换处理
for (Object item : paras) {
String str = StringHelper.toString(item);
if (str == null || item instanceof Number || item.getClass().isEnum() || item instanceof Boolean) {
if (str == null) {
sql = sql.replaceFirst("\\?", "null");
} else {
sql = sql.replaceFirst("\\?", str);
}
} else {
sql = sql.replaceFirst("\\?", "'" + str.replace("'", "''") + "'");
}
}
Log.infoTag(DbExecuteImpl.class, String.format("%d row", row), sql);
}
}
package com.yanzuoguang.db.db.extend;
/**
* 打印SQL日志
*/
public class ConfigDb {
/**
* 打印映射日志
*/
public static final boolean PrintMapper = false;
/**
* 打印SQL日志
*/
public static boolean PrintSql = false;
/**
* 判断是否匹配过滤
*/
public static String PrintSqlFilter = "";
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment