|
@@ -0,0 +1,942 @@
|
|
|
+package com.gyee.dao;
|
|
|
+
|
|
|
+import java.beans.IntrospectionException;
|
|
|
+import java.beans.PropertyDescriptor;
|
|
|
+import java.io.Serializable;
|
|
|
+import java.lang.reflect.Field;
|
|
|
+import java.lang.reflect.InvocationTargetException;
|
|
|
+import java.lang.reflect.Method;
|
|
|
+import java.sql.Connection;
|
|
|
+import java.sql.PreparedStatement;
|
|
|
+import java.sql.ResultSet;
|
|
|
+import java.sql.SQLException;
|
|
|
+import java.sql.Types;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.HashSet;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Set;
|
|
|
+
|
|
|
+import org.apache.commons.logging.Log;
|
|
|
+import org.apache.commons.logging.LogFactory;
|
|
|
+import org.springframework.jdbc.core.JdbcTemplate;
|
|
|
+import org.springframework.jdbc.core.PreparedStatementCreator;
|
|
|
+import org.springframework.jdbc.core.RowMapper;
|
|
|
+import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
|
|
|
+import org.springframework.jdbc.support.GeneratedKeyHolder;
|
|
|
+import org.springframework.jdbc.support.KeyHolder;
|
|
|
+import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
|
|
|
+
|
|
|
+import com.gyee.util.BeanFactoryUtils;
|
|
|
+import com.gyee.util.DataBaseHelper;
|
|
|
+import com.gyee.util.EntitySQLHelper;
|
|
|
+import com.gyee.util.PaginationList;
|
|
|
+import com.gyee.util.QueryOrder;
|
|
|
+import com.gyee.util.StringUtils;
|
|
|
+import com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException;
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+/**
|
|
|
+ *
|
|
|
+ * @author shilinno1
|
|
|
+ *
|
|
|
+ */
|
|
|
+public class JdbcDaoTemplate extends JdbcTemplate {
|
|
|
+
|
|
|
+ protected final Log logger = LogFactory.getLog(getClass());
|
|
|
+
|
|
|
+ public OracleSequenceMaxValueIncrementer sequence = BeanFactoryUtils.getBean("sequence", OracleSequenceMaxValueIncrementer.class);
|
|
|
+
|
|
|
+ public void save(String prefix, List<String> list) {
|
|
|
+
|
|
|
+ if (!list.isEmpty()) {
|
|
|
+ for (String str : list) {
|
|
|
+ try {
|
|
|
+ // 保存sql后缀
|
|
|
+ StringBuffer suffix = new StringBuffer();
|
|
|
+ Connection conn = getDataSource().getConnection();
|
|
|
+ // 设置事务为非自动提交
|
|
|
+ conn.setAutoCommit(false);
|
|
|
+ // Statement st = conn.createStatement();
|
|
|
+ // 比起st,pst会更好些
|
|
|
+ PreparedStatement pst = conn.prepareStatement("");
|
|
|
+ // 外层循环,总提交事务次数
|
|
|
+ for (int i = 0; i < list.size(); i++) {
|
|
|
+
|
|
|
+ suffix.append(list.get(i));
|
|
|
+ // 构建完整sql
|
|
|
+ String sql = prefix + suffix.substring(0, suffix.length() - 1);
|
|
|
+ // 添加执行sql
|
|
|
+ pst.addBatch(sql);
|
|
|
+ // 执行操作
|
|
|
+ pst.executeBatch();
|
|
|
+ // 提交事务
|
|
|
+ conn.commit();
|
|
|
+ // 清空上一次添加的数据
|
|
|
+ suffix = new StringBuffer();
|
|
|
+ }
|
|
|
+ // 头等连接
|
|
|
+ pst.close();
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 按主键删除对象
|
|
|
+ *
|
|
|
+ * @param clazz
|
|
|
+ * @param id
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ public void delete(Class clazz, Serializable id) {
|
|
|
+ String pk = null;
|
|
|
+ ResultSet resultSet = null;
|
|
|
+ Connection conn = null;
|
|
|
+ try {
|
|
|
+ conn = getDataSource().getConnection();
|
|
|
+ resultSet = conn.getMetaData().getPrimaryKeys(null, null, clazz.getSimpleName().toUpperCase());
|
|
|
+ if (!resultSet.isAfterLast()) {
|
|
|
+ resultSet.next();
|
|
|
+ pk = resultSet.getString("COLUMN_NAME");
|
|
|
+ }
|
|
|
+ } catch (SQLException e) {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ logger.debug("数据库连接异常,获取数据库元数据MetaData出错!");
|
|
|
+ e.printStackTrace();
|
|
|
+ } finally {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ resultSet = null;
|
|
|
+ }
|
|
|
+ String sql = String.format("delete from %1$s where %2$s = ?", clazz.getSimpleName().toUpperCase(), pk);
|
|
|
+ update(sql, new Object[] { id });
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 按多主键删除表
|
|
|
+ *
|
|
|
+ * @param tableName
|
|
|
+ * @param pks
|
|
|
+ */
|
|
|
+ @Deprecated
|
|
|
+ public void delete(String tableName, Object[] pks) {
|
|
|
+ String sql = EntitySQLHelper.generateDeleteByPKSql(tableName.toUpperCase(), DataBaseHelper.getTablePrimaryKeyFieldNames(tableName, getDataSource()));
|
|
|
+ update(sql, pks);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 分页查询当前Class对应的实体表所有记录
|
|
|
+ *
|
|
|
+ * @param clazz
|
|
|
+ * @param offset
|
|
|
+ * @param maxResults
|
|
|
+ * @param orders
|
|
|
+ * @return
|
|
|
+ * @throws JdbcDaoException
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ public PaginationList findAll(Class clazz, int offset, int maxResults, QueryOrder... orders) throws JdbcDaoException {
|
|
|
+ StringBuilder sb = new StringBuilder();
|
|
|
+ sb.append(String.format("select * from %1$s", clazz.getSimpleName().toUpperCase()));
|
|
|
+ int total = queryForInt(String.format("select count(0) from %1$s", clazz.getSimpleName().toUpperCase()));
|
|
|
+ if (orders.length > 1) {
|
|
|
+ for (int i = 0; i < orders.length; i++) {
|
|
|
+ if (orders[i] != null)
|
|
|
+ orders[i].appendSqlOrder(sb);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ setLimitResult(sb, offset, maxResults);
|
|
|
+ return new PaginationList(query(sb.toString(), ParameterizedBeanPropertyRowMapper.newInstance(clazz)), total);
|
|
|
+ }
|
|
|
+
|
|
|
+ // =====================================
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 查询当前Class对应的实体表所有记录
|
|
|
+ *
|
|
|
+ * @param clazz
|
|
|
+ * @param orders
|
|
|
+ * @return
|
|
|
+ * @throws JdbcDaoException
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ public List findAll(Class clazz, QueryOrder... orders) {
|
|
|
+ StringBuilder sb = new StringBuilder();
|
|
|
+ sb.append(String.format("select * from %1$s", clazz.getSimpleName().toUpperCase()));
|
|
|
+ int total = queryForInt(String.format("select count(0) from %1$s", clazz.getSimpleName().toUpperCase()));
|
|
|
+ if (orders.length > 0) {
|
|
|
+ for (int i = 0; i < orders.length; i++) {
|
|
|
+ if (orders[i] != null)
|
|
|
+ orders[i].appendSqlOrder(sb);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return new PaginationList(query(sb.toString(), ParameterizedBeanPropertyRowMapper.newInstance(clazz)), total);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 占位符sql查询分页
|
|
|
+ *
|
|
|
+ * @param sql
|
|
|
+ * @param objects
|
|
|
+ * @param offset
|
|
|
+ * @param maxResults
|
|
|
+ * @param rowMapper
|
|
|
+ * @param orders
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ public PaginationList findNativeBySql(String sql, Object[] objects, int offset, int maxResults, RowMapper rowMapper, QueryOrder... orders) {
|
|
|
+ StringBuilder sb = new StringBuilder(sql);
|
|
|
+ int total = -1;
|
|
|
+ StringBuilder totalSQL = new StringBuilder(" SELECT count(*) FROM ( ");
|
|
|
+ totalSQL.append(sb.toString());
|
|
|
+ totalSQL.append(" ) totalTable ");
|
|
|
+ total = queryForInt(totalSQL.toString(), objects);
|
|
|
+ if (orders.length > 1) {
|
|
|
+ for (int i = 0; i < orders.length; i++) {
|
|
|
+ if (orders[i] != null)
|
|
|
+ orders[i].appendSqlOrder(sb);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ setLimitResult(sb, offset, maxResults); // 添加数据抓取
|
|
|
+ return new PaginationList(query(sb.toString(), objects, rowMapper), total);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * @param sql
|
|
|
+ * @param objects
|
|
|
+ * @param rowMapper
|
|
|
+ * @return
|
|
|
+ * @throws JdbcDaoException
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ public List findNativeBySql(String sql, Object[] objects, RowMapper rowMapper) throws JdbcDaoException {
|
|
|
+ List queryList = query(sql, objects, rowMapper);
|
|
|
+ return new PaginationList(queryList, queryList.size());
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 占位符sql查询
|
|
|
+ *
|
|
|
+ * @param sql
|
|
|
+ * @param objects
|
|
|
+ * @param rowMapper
|
|
|
+ * @param orders
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ public List findNativeBySql(String sql, Object[] objects, RowMapper rowMapper, QueryOrder... orders) {
|
|
|
+ StringBuilder sb = new StringBuilder(sql);
|
|
|
+ if (orders.length > 1) {
|
|
|
+ for (int i = 0; i < orders.length; i++) {
|
|
|
+ if (orders[i] != null)
|
|
|
+ orders[i].appendSqlOrder(sb);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return query(sb.toString(), objects, rowMapper);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 获取单主键对象(数据库表名与类名,数据库字段名与类属性相同)
|
|
|
+ *
|
|
|
+ * @param clazz
|
|
|
+ * @param id
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ public Object get(Class clazz, Serializable id) {
|
|
|
+ String pk = null;
|
|
|
+ Connection conn = null;
|
|
|
+ ResultSet resultSet = null;
|
|
|
+ try {
|
|
|
+ conn = getDataSource().getConnection();
|
|
|
+ resultSet = conn.getMetaData().getPrimaryKeys(null, null, clazz.getSimpleName().toUpperCase());
|
|
|
+ if (!resultSet.isAfterLast()) {
|
|
|
+ resultSet.next();
|
|
|
+ pk = resultSet.getString("COLUMN_NAME");
|
|
|
+ }
|
|
|
+ } catch (MySQLSyntaxErrorException e) {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ throw new JdbcDaoException("根据主键获取对象失败,当前对象的类名 '" + clazz.getSimpleName().toUpperCase() + "' 与对应的数据库表名不一致!");
|
|
|
+ } catch (SQLException e) {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e2) {
|
|
|
+ e2.printStackTrace();
|
|
|
+ }
|
|
|
+ throw new JdbcDaoException("通过元数据操作数据库异常:", new Throwable(e));
|
|
|
+ } finally {
|
|
|
+ resultSet = null;
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e2) {
|
|
|
+ e2.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Set<String> set = new HashSet<String>();
|
|
|
+ set.add(pk);
|
|
|
+ String sql = EntitySQLHelper.generateSelectByPKSql(clazz.getSimpleName().toUpperCase(), set);
|
|
|
+ // String sql = String.format("select * from %1$s where %2$s = ?" ,
|
|
|
+ // clazz.getSimpleName(),pk);
|
|
|
+ logger.info("通过主键获取对象的sql语句: " + sql);
|
|
|
+ return queryForObject(sql, new Object[] { id }, ParameterizedBeanPropertyRowMapper.newInstance(clazz));
|
|
|
+ }
|
|
|
+
|
|
|
+ // /**
|
|
|
+ // * 保存
|
|
|
+ // * @param tableName
|
|
|
+ // * @param paramValues
|
|
|
+ // * @return
|
|
|
+ // */
|
|
|
+ // public long save(String tableName,final Object[] paramValues){
|
|
|
+ // Set<String> columns = getTableFieldNames(tableName);
|
|
|
+ // Set<String> pks = getTablePrimaryKeyFieldNames(tableName);
|
|
|
+ // final String sql = EntitySQLHelper.generateInsertSql(columns, tableName,
|
|
|
+ // true, pks);
|
|
|
+ //
|
|
|
+ // KeyHolder key = new GeneratedKeyHolder();
|
|
|
+ // update(new PreparedStatementCreator() {
|
|
|
+ //
|
|
|
+ // @Override
|
|
|
+ // public PreparedStatement createPreparedStatement(Connection con) throws
|
|
|
+ // SQLException {
|
|
|
+ //
|
|
|
+ // PreparedStatement ps =
|
|
|
+ // con.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
|
|
|
+ //
|
|
|
+ // for (int i = 0; i < paramValues.length; ++i) {
|
|
|
+ // Object obj = paramValues[i];
|
|
|
+ // if (null == obj) {
|
|
|
+ // ps.setNull(i + 1, Types.CHAR);
|
|
|
+ // } else if (obj instanceof java.sql.Date) {
|
|
|
+ // ps.setDate(i + 1, (java.sql.Date) obj);
|
|
|
+ // } else if (obj instanceof java.sql.Timestamp) {
|
|
|
+ // ps.setTimestamp(i + 1, (java.sql.Timestamp) obj);
|
|
|
+ // } else {
|
|
|
+ // ps.setObject(i + 1, obj);
|
|
|
+ // }
|
|
|
+ // }
|
|
|
+ // return ps;
|
|
|
+ // }
|
|
|
+ //
|
|
|
+ // },key);
|
|
|
+ // return key.getKey().intValue();
|
|
|
+ // }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 多主键,或者单主键获取指定类型的对象
|
|
|
+ *
|
|
|
+ * @param clazz
|
|
|
+ * @param id
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ public Object get(String tableName, Class clazz, Object[] pk) {
|
|
|
+ Set<String> pks = DataBaseHelper.getTablePrimaryKeyFieldNames(tableName.toUpperCase(), getDataSource());
|
|
|
+ String sql = EntitySQLHelper.generateSelectByPKSql(tableName.toUpperCase(), pks);
|
|
|
+ logger.info("通过主键获取对象的sql语句: " + sql);
|
|
|
+ return queryForObject(sql, pk, ParameterizedBeanPropertyRowMapper.newInstance(clazz));
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 获取单主键对象(数据库字段名与类属性相同)
|
|
|
+ *
|
|
|
+ * @param tableName
|
|
|
+ * @param clazz
|
|
|
+ * @param id
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ public Object get(String tableName, Class clazz, Serializable id) {
|
|
|
+ String pk = null;
|
|
|
+ Connection conn = null;
|
|
|
+ ResultSet resultSet = null;
|
|
|
+ try {
|
|
|
+ conn = getDataSource().getConnection();
|
|
|
+ resultSet = conn.getMetaData().getPrimaryKeys(null, null, tableName.toUpperCase());
|
|
|
+ if (!resultSet.isAfterLast()) {
|
|
|
+ resultSet.next();
|
|
|
+ pk = resultSet.getString("COLUMN_NAME");
|
|
|
+ }
|
|
|
+ } catch (MySQLSyntaxErrorException e) {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ throw new JdbcDaoException("根据主键获取对象失败,当前对象的类名 '" + clazz.getSimpleName().toUpperCase() + "' 与对应的数据库表名不一致!");
|
|
|
+ } catch (SQLException e) {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ throw new JdbcDaoException("通过元数据操作数据库异常:", new Throwable(e));
|
|
|
+ } finally {
|
|
|
+ resultSet = null;
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Set<String> set = new HashSet<String>();
|
|
|
+ set.add(pk);
|
|
|
+ String sql = EntitySQLHelper.generateSelectByPKSql(clazz.getSimpleName().toUpperCase(), set);
|
|
|
+ // String sql = String.format("select * from %1$s where %2$s = ?" ,
|
|
|
+ // clazz.getSimpleName(),pk);
|
|
|
+ logger.info("通过主键获取对象的sql语句: " + sql);
|
|
|
+ return queryForObject(sql, new Object[] { id }, ParameterizedBeanPropertyRowMapper.newInstance(clazz));
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 多主键,或者单主键获取对象
|
|
|
+ *
|
|
|
+ * @param tableName
|
|
|
+ * @param pk
|
|
|
+ * @param rowMapper
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public Object get(String tableName, Object[] pk, RowMapper rowMapper) {
|
|
|
+ Set<String> pks = DataBaseHelper.getTablePrimaryKeyFieldNames(tableName.toUpperCase(), getDataSource());
|
|
|
+ String sql = EntitySQLHelper.generateSelectByPKSql(tableName.toUpperCase(), pks);
|
|
|
+ logger.info("通过主键获取对象的sql语句: " + sql);
|
|
|
+ return queryForObject(sql, pk, rowMapper);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 获取单主键对象
|
|
|
+ *
|
|
|
+ * @param tableName
|
|
|
+ * @param id
|
|
|
+ * @param rowMapper
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public Object get(String tableName, Serializable id, RowMapper rowMapper) {
|
|
|
+ String pk = null;
|
|
|
+ Connection conn = null;
|
|
|
+ ResultSet resultSet = null;
|
|
|
+ try {
|
|
|
+ conn = getDataSource().getConnection();
|
|
|
+ resultSet = conn.getMetaData().getPrimaryKeys(null, null, tableName.toUpperCase());
|
|
|
+ if (!resultSet.isAfterLast()) {
|
|
|
+ resultSet.next();
|
|
|
+ pk = resultSet.getString("COLUMN_NAME");
|
|
|
+ }
|
|
|
+ } catch (SQLException e) {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ throw new JdbcDaoException("通过元数据操作数据库异常:", new Throwable(e));
|
|
|
+ } finally {
|
|
|
+ resultSet = null;
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ Set<String> set = new HashSet<String>();
|
|
|
+ set.add(pk);
|
|
|
+ String sql = EntitySQLHelper.generateSelectByPKSql(tableName.toUpperCase(), set);
|
|
|
+ // String sql = String.format("select * from %1$s where %2$s = ?" ,
|
|
|
+ // tableName, pk);
|
|
|
+ logger.info("通过主键获取对象的sql语句: " + sql);
|
|
|
+ return queryForObject(sql, new Object[] { id }, rowMapper);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 增加并且获取主键
|
|
|
+ *
|
|
|
+ * @param sql
|
|
|
+ * @param params
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public Number insertAndGetKey(final String sql) {
|
|
|
+ logger.debug("Executing SQL update and returning generated keys");
|
|
|
+ final KeyHolder key = new GeneratedKeyHolder();
|
|
|
+ update(new PreparedStatementCreator() {
|
|
|
+ public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
|
|
|
+ PreparedStatement ps = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
|
|
|
+ return ps;
|
|
|
+ }
|
|
|
+ }, key);
|
|
|
+ return key.getKey();
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 保存对象
|
|
|
+ *
|
|
|
+ * @param o
|
|
|
+ * @return
|
|
|
+ * @throws JdbcDaoException
|
|
|
+ * @throws IntrospectionException
|
|
|
+ * @throws IllegalArgumentException
|
|
|
+ * @throws IllegalAccessException
|
|
|
+ * @throws InvocationTargetException
|
|
|
+ */
|
|
|
+ public Object save(Object o, boolean flagAcr) throws JdbcDaoException, IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
|
|
|
+ String pk = null;
|
|
|
+ ResultSet resultSet = null;
|
|
|
+ Connection conn = null;
|
|
|
+
|
|
|
+ try {
|
|
|
+ conn = getDataSource().getConnection();
|
|
|
+ resultSet = conn.getMetaData().getColumns(null, null, o.getClass().getSimpleName().toUpperCase(), null);
|
|
|
+ if (!resultSet.isAfterLast()) {
|
|
|
+ resultSet.next();
|
|
|
+ pk = resultSet.getString("COLUMN_NAME");
|
|
|
+ }
|
|
|
+ } catch (SQLException e) {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ throw new JdbcDaoException("数据库连接异常,获取数据库元数据MetaData出错!");
|
|
|
+ // e.printStackTrace();
|
|
|
+ } finally {
|
|
|
+ resultSet = null;
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ String obj = new String();
|
|
|
+ Field[] fields = o.getClass().getDeclaredFields();
|
|
|
+ StringBuilder fieldBuffer = new StringBuilder();
|
|
|
+ StringBuilder valueBuilder = new StringBuilder();
|
|
|
+ final List<Object> valueObjects = new ArrayList<Object>();
|
|
|
+ fieldBuffer.append("insert into " + o.getClass().getSimpleName().toUpperCase() + " (");
|
|
|
+ valueBuilder.append(") values(");
|
|
|
+
|
|
|
+ for (Field field : fields) {
|
|
|
+ if (flagAcr) {
|
|
|
+ // if (!field.getName().toUpperCase().equals(pk.toUpperCase())
|
|
|
+
|
|
|
+ // ) {
|
|
|
+ // PropertyDescriptor pd = null;
|
|
|
+ try {
|
|
|
+ // pd = new PropertyDescriptor(field.getName(),
|
|
|
+ // o.getClass());
|
|
|
+ StringBuilder getMethodName = new StringBuilder();
|
|
|
+
|
|
|
+ getMethodName.append("get");
|
|
|
+ getMethodName.append(field.getName().substring(0, 1).toUpperCase());
|
|
|
+ getMethodName.append(field.getName().substring(1));
|
|
|
+
|
|
|
+ Method getMethod = o.getClass().getMethod(String.valueOf(getMethodName), new Class[] {});
|
|
|
+ // Method getMethod = pd.getReadMethod();
|
|
|
+ if (field.getName().toUpperCase().equals(pk.toUpperCase())) {
|
|
|
+ fieldBuffer.append(field.getName().toUpperCase() + ",");
|
|
|
+ valueBuilder.append("? ,");
|
|
|
+
|
|
|
+ if (field.getType() == Long.class) {
|
|
|
+ Long temp = sequence.nextLongValue();
|
|
|
+ obj = String.valueOf(temp);
|
|
|
+ valueObjects.add(temp);
|
|
|
+ } else if (field.getType() == Integer.class) {
|
|
|
+ Integer temp = sequence.nextIntValue();
|
|
|
+ obj = String.valueOf(temp);
|
|
|
+ valueObjects.add(temp);
|
|
|
+
|
|
|
+ } else if (field.getType() == String.class) {
|
|
|
+
|
|
|
+ if (StringUtils.notEmp(getMethod.invoke(o))) {
|
|
|
+ valueObjects.add(getMethod.invoke(o));
|
|
|
+
|
|
|
+ } else {
|
|
|
+ // String temp=GeneralUUIDHelper.newId();
|
|
|
+ // //String temp=sequence.nextStringValue();
|
|
|
+ // obj=temp;
|
|
|
+ Long temp = sequence.nextLongValue();
|
|
|
+ obj = String.valueOf(temp);
|
|
|
+ valueObjects.add(obj);
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ } else {
|
|
|
+ // if (getMethod.invoke(o) != null) {
|
|
|
+ fieldBuffer.append(field.getName().toUpperCase() + ",");
|
|
|
+ valueBuilder.append("? ,");
|
|
|
+ valueObjects.add(getMethod.invoke(o));
|
|
|
+ // }
|
|
|
+ }
|
|
|
+
|
|
|
+ } catch (Exception e) {
|
|
|
+ logger.debug("调用反射获取PropertyDescriptor时抛出异常:");
|
|
|
+ // e.printStackTrace();
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ // }
|
|
|
+ /*
|
|
|
+ * else if
|
|
|
+ * (field.getName().toUpperCase().equals(pk.toUpperCase())) {
|
|
|
+ * PropertyDescriptor pd = null; try { pd = new
|
|
|
+ * PropertyDescriptor(pk, o.getClass()); Method getMethod =
|
|
|
+ * pd.getReadMethod(); if (getMethod.invoke(o) != null) {
|
|
|
+ * fieldBuffer.append(field.getName().toUpperCase() + ",");
|
|
|
+ * valueBuilder.append("? ,");
|
|
|
+ *
|
|
|
+ * if (field.getType() == Long.class) {
|
|
|
+ * valueObjects.add(sequence.nextLongValue());; } else if
|
|
|
+ * (field.getType() == Integer.class) {
|
|
|
+ * valueObjects.add(sequence.nextIntValue());; } else if
|
|
|
+ * (field.getType() == String.class) {
|
|
|
+ * valueObjects.add(sequence.nextStringValue());; } } } catch
|
|
|
+ * (Exception e) {
|
|
|
+ * logger.debug("调用反射获取PropertyDescriptor时抛出异常:"); //
|
|
|
+ * e.printStackTrace(); continue; } }
|
|
|
+ */
|
|
|
+ } else {
|
|
|
+ PropertyDescriptor pd = null;
|
|
|
+ try {
|
|
|
+ pd = new PropertyDescriptor(field.getName(), o.getClass());
|
|
|
+ Method getMethod = pd.getReadMethod();
|
|
|
+ if (getMethod.invoke(o) != null) {
|
|
|
+ fieldBuffer.append(field.getName() + ",");
|
|
|
+ valueBuilder.append("? ,");
|
|
|
+ valueObjects.add(getMethod.invoke(o));
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ logger.debug("调用反射获取PropertyDescriptor时抛出异常:");
|
|
|
+ // e.printStackTrace();
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+ final String sql = fieldBuffer.toString().substring(0, fieldBuffer.toString().lastIndexOf(",")) + valueBuilder.toString().substring(0, valueBuilder.toString().lastIndexOf(",")) + " )";
|
|
|
+
|
|
|
+ if (flagAcr) {
|
|
|
+ KeyHolder key = new GeneratedKeyHolder();
|
|
|
+
|
|
|
+ update(new PreparedStatementCreator() {
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
|
|
|
+
|
|
|
+ PreparedStatement ps = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
|
|
|
+
|
|
|
+ Object[] params = valueObjects.toArray();
|
|
|
+ for (int i = 0; i < params.length; ++i) {
|
|
|
+ Object obj = params[i];
|
|
|
+ if (null == obj) {
|
|
|
+ ps.setNull(i + 1, Types.CHAR);
|
|
|
+ } else if (obj instanceof java.sql.Date) {
|
|
|
+ ps.setDate(i + 1, (java.sql.Date) obj);
|
|
|
+ } else if (obj instanceof java.sql.Timestamp) {
|
|
|
+ ps.setTimestamp(i + 1, (java.sql.Timestamp) obj);
|
|
|
+ } else if (obj instanceof java.util.Date) {
|
|
|
+
|
|
|
+ java.util.Date date = (java.util.Date) obj;
|
|
|
+ ps.setTimestamp(i + 1, new java.sql.Timestamp(date.getTime()));
|
|
|
+ } else {
|
|
|
+ ps.setObject(i + 1, obj);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return ps;
|
|
|
+ }
|
|
|
+
|
|
|
+ }, key);
|
|
|
+
|
|
|
+ Field pkField = null;
|
|
|
+ for (Field field : fields) {
|
|
|
+ if (field.getName().toUpperCase().equals(pk.toUpperCase())) {
|
|
|
+ pk = field.getName();
|
|
|
+ pkField = field;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ PropertyDescriptor pd1 = new PropertyDescriptor(pk, o.getClass());
|
|
|
+ Method setMethod = pd1.getWriteMethod();
|
|
|
+ if (pkField.getType() == Long.class) {
|
|
|
+ setMethod.invoke(o, Long.valueOf(obj));
|
|
|
+ } else if (pkField.getType() == Integer.class) {
|
|
|
+ setMethod.invoke(o, Integer.valueOf(obj));
|
|
|
+ } else if (pkField.getType() == String.class) {
|
|
|
+ setMethod.invoke(o, String.valueOf(obj));
|
|
|
+ }
|
|
|
+ return o;
|
|
|
+ } else {
|
|
|
+ update(new PreparedStatementCreator() {
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
|
|
|
+
|
|
|
+ PreparedStatement ps = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
|
|
|
+
|
|
|
+ Object[] params = valueObjects.toArray();
|
|
|
+ for (int i = 0; i < params.length; ++i) {
|
|
|
+ Object obj = params[i];
|
|
|
+ if (null == obj) {
|
|
|
+ ps.setNull(i + 1, Types.CHAR);
|
|
|
+ } else if (obj instanceof java.sql.Date) {
|
|
|
+ ps.setDate(i + 1, (java.sql.Date) obj);
|
|
|
+ } else if (obj instanceof java.sql.Timestamp) {
|
|
|
+ ps.setTimestamp(i + 1, (java.sql.Timestamp) obj);
|
|
|
+ } else if (obj instanceof java.util.Date) {
|
|
|
+
|
|
|
+ java.util.Date date = (java.util.Date) obj;
|
|
|
+
|
|
|
+ ps.setDate(i + 1, new java.sql.Date(date.getTime()));
|
|
|
+ } else {
|
|
|
+ ps.setObject(i + 1, obj);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return ps;
|
|
|
+ }
|
|
|
+
|
|
|
+ });
|
|
|
+
|
|
|
+ for (Field field : fields) {
|
|
|
+ if (field.getName().toUpperCase().equals(pk.toUpperCase())) {
|
|
|
+ pk = field.getName();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ PropertyDescriptor pd1 = new PropertyDescriptor(pk, o.getClass());
|
|
|
+ Method getMethod = pd1.getReadMethod();
|
|
|
+ return get(o.getClass(), (Serializable) getMethod.invoke(o));
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 保存对象,适用类名与表名不匹配,但是字段和属性匹配。
|
|
|
+ *
|
|
|
+ * @param tableName
|
|
|
+ * @param o
|
|
|
+ * @return
|
|
|
+ * @throws JdbcDaoException
|
|
|
+ * @throws IntrospectionException
|
|
|
+ * @throws IllegalArgumentException
|
|
|
+ * @throws IllegalAccessException
|
|
|
+ * @throws InvocationTargetException
|
|
|
+ */
|
|
|
+ public Object save(String tableName, Object o) throws JdbcDaoException, IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
|
|
|
+ String pk = null;
|
|
|
+ Connection conn = null;
|
|
|
+ ResultSet resultSet = null;
|
|
|
+ try {
|
|
|
+ conn = getDataSource().getConnection();
|
|
|
+ resultSet = conn.getMetaData().getColumns(null, null, tableName.toUpperCase(), null);
|
|
|
+ if (!resultSet.isAfterLast()) {
|
|
|
+ resultSet.next();
|
|
|
+ pk = resultSet.getString("COLUMN_NAME");
|
|
|
+ }
|
|
|
+ } catch (SQLException e) {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ throw new JdbcDaoException("数据库连接异常,获取数据库元数据MetaData出错!");
|
|
|
+ // e.printStackTrace();
|
|
|
+ } finally {
|
|
|
+ resultSet = null;
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ Field[] fields = o.getClass().getDeclaredFields();
|
|
|
+ StringBuilder fieldBuffer = new StringBuilder();
|
|
|
+ StringBuilder valueBuilder = new StringBuilder();
|
|
|
+ final List<Object> valueObjects = new ArrayList<Object>();
|
|
|
+ fieldBuffer.append("insert into " + tableName.toUpperCase() + " (");
|
|
|
+ valueBuilder.append(") values(");
|
|
|
+ for (Field field : fields) {
|
|
|
+ if (!field.getName().toUpperCase().equals(pk.toUpperCase())) {
|
|
|
+ PropertyDescriptor pd;
|
|
|
+ try {
|
|
|
+ pd = new PropertyDescriptor(field.getName(), o.getClass());
|
|
|
+ Method getMethod = pd.getReadMethod();
|
|
|
+ if (getMethod.invoke(o) != null) {
|
|
|
+ fieldBuffer.append(field.getName() + ",");
|
|
|
+ valueBuilder.append("? ,");
|
|
|
+ valueObjects.add(getMethod.invoke(o));
|
|
|
+ }
|
|
|
+ } catch (IntrospectionException e) {
|
|
|
+ logger.debug("调用反射获取PropertyDescriptor时抛出异常:");
|
|
|
+ // e.printStackTrace();
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ final String sql = fieldBuffer.toString().substring(0, fieldBuffer.toString().lastIndexOf(",")) + valueBuilder.toString().substring(0, valueBuilder.toString().lastIndexOf(",")) + " )";
|
|
|
+
|
|
|
+ KeyHolder key = new GeneratedKeyHolder();
|
|
|
+ update(new PreparedStatementCreator() {
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
|
|
|
+
|
|
|
+ PreparedStatement ps = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
|
|
|
+
|
|
|
+ Object[] params = valueObjects.toArray();
|
|
|
+ for (int i = 0; i < params.length; ++i) {
|
|
|
+ Object obj = params[i];
|
|
|
+ if (null == obj) {
|
|
|
+ ps.setNull(i + 1, Types.CHAR);
|
|
|
+ } else if (obj instanceof java.sql.Date) {
|
|
|
+ ps.setDate(i + 1, (java.sql.Date) obj);
|
|
|
+ } else if (obj instanceof java.sql.Timestamp) {
|
|
|
+ ps.setTimestamp(i + 1, (java.sql.Timestamp) obj);
|
|
|
+ } else if (obj instanceof java.util.Date) {
|
|
|
+
|
|
|
+ java.util.Date date = (java.util.Date) obj;
|
|
|
+ ps.setTimestamp(i + 1, new java.sql.Timestamp(date.getTime()));
|
|
|
+ } else {
|
|
|
+ ps.setObject(i + 1, obj);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return ps;
|
|
|
+ }
|
|
|
+
|
|
|
+ }, key);
|
|
|
+
|
|
|
+ for (Field field : fields) {
|
|
|
+ if (field.getName().toUpperCase().equals(pk.toUpperCase())) {
|
|
|
+ pk = field.getName();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ PropertyDescriptor pd = new PropertyDescriptor(pk, o.getClass());
|
|
|
+ Method setMethod = pd.getWriteMethod();
|
|
|
+ setMethod.invoke(o, sequence.nextStringValue());
|
|
|
+ return o;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 设置抓取记录
|
|
|
+ *
|
|
|
+ * @param sb
|
|
|
+ * @param offset
|
|
|
+ * @param maxResults
|
|
|
+ */
|
|
|
+ public void setLimitResult(StringBuilder sb, int offset, int maxResults) {
|
|
|
+ if (sb != null)
|
|
|
+ sb.append(" Limit ").append(offset).append(", ").append(maxResults);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 更新对象
|
|
|
+ *
|
|
|
+ * @param o
|
|
|
+ * @return
|
|
|
+ * @throws JdbcDaoException
|
|
|
+ * @throws IntrospectionException
|
|
|
+ * @throws IllegalArgumentException
|
|
|
+ * @throws IllegalAccessException
|
|
|
+ * @throws InvocationTargetException
|
|
|
+ */
|
|
|
+ public void update(Object o) throws JdbcDaoException, IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
|
|
|
+ String pk = null;
|
|
|
+ Object pkValue = null;
|
|
|
+ ResultSet resultSet = null;
|
|
|
+ Connection conn = null;
|
|
|
+ try {
|
|
|
+ conn = getDataSource().getConnection();
|
|
|
+ resultSet = conn.getMetaData().getColumns(null, null, o.getClass().getSimpleName().toUpperCase(), null);
|
|
|
+ if (!resultSet.isAfterLast()) {
|
|
|
+ resultSet.next();
|
|
|
+ pk = resultSet.getString("COLUMN_NAME");
|
|
|
+ }
|
|
|
+ } catch (SQLException e) {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ e.printStackTrace();
|
|
|
+ } finally {
|
|
|
+ try {
|
|
|
+ conn.close();
|
|
|
+ } catch (SQLException e1) {
|
|
|
+ e1.printStackTrace();
|
|
|
+ }
|
|
|
+ resultSet = null;
|
|
|
+ }
|
|
|
+
|
|
|
+ Field[] fields = o.getClass().getDeclaredFields();
|
|
|
+ StringBuilder sqlBuffer = new StringBuilder();
|
|
|
+ final List<Object> valueObjects = new ArrayList<Object>();
|
|
|
+ sqlBuffer.append("UPDATE " + o.getClass().getSimpleName().toUpperCase() + " SET ");
|
|
|
+ for (Field field : fields) {
|
|
|
+ PropertyDescriptor pd = null;
|
|
|
+ try {
|
|
|
+ pd = new PropertyDescriptor(field.getName(), o.getClass());
|
|
|
+ Method getMethod = pd.getReadMethod();
|
|
|
+ if (!field.getName().toUpperCase().equals(pk.toUpperCase())) {
|
|
|
+ if (getMethod.invoke(o) != null) {
|
|
|
+ sqlBuffer.append(field.getName() + " = ? ,");
|
|
|
+ valueObjects.add(getMethod.invoke(o));
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ pkValue = getMethod.invoke(o);
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ logger.debug("调用反射获取PropertyDescriptor时抛出异常:");
|
|
|
+ // e.printStackTrace();
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+ valueObjects.add(pkValue);
|
|
|
+
|
|
|
+ final String sql = sqlBuffer.toString().substring(0, sqlBuffer.toString().length() - 1) + "where " + pk + " = ?";
|
|
|
+
|
|
|
+ update(new PreparedStatementCreator() {
|
|
|
+ @Override
|
|
|
+ public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
|
|
|
+ PreparedStatement ps = con.prepareStatement(sql);
|
|
|
+
|
|
|
+ Object[] params = valueObjects.toArray();
|
|
|
+ for (int i = 0; i < params.length; ++i) {
|
|
|
+ Object obj = params[i];
|
|
|
+ if (null == obj) {
|
|
|
+ ps.setNull(i + 1, Types.CHAR);
|
|
|
+ } else if (obj instanceof java.sql.Date) {
|
|
|
+ ps.setDate(i + 1, (java.sql.Date) obj);
|
|
|
+ } else if (obj instanceof java.sql.Timestamp) {
|
|
|
+ ps.setTimestamp(i + 1, (java.sql.Timestamp) obj);
|
|
|
+ } else if (obj instanceof java.util.Date) {
|
|
|
+
|
|
|
+ java.util.Date date = (java.util.Date) obj;
|
|
|
+ ps.setTimestamp(i + 1, new java.sql.Timestamp(date.getTime()));
|
|
|
+ // ps.setDate(i + 1, new java.sql.Date(date.getTime()));
|
|
|
+ } else {
|
|
|
+ ps.setObject(i + 1, obj);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return ps;
|
|
|
+ }
|
|
|
+
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+}
|