From ab78e9de8cd2987e951310aa9215b21eeb906a43 Mon Sep 17 00:00:00 2001 From: 王彬 Date: Fri, 23 Apr 2021 10:40:26 +0800 Subject: [PATCH] 1.upgrade repository version --- build.gradle | 6 ++---- src/main/java/com/taover/repository/CustomJdbcTemplate.java | 929 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/taover/repository/CustomJdbcTemplateBroadcast.java | 602 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/taover/repository/CustomJdbcTemplateBroadcastInterface.java | 153 --------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/taover/repository/CustomJdbcTemplateWrapperTenant.java | 12 ++++++++---- src/main/java/com/taover/repository/advice/EntityPointCut.java | 8 -------- src/main/java/com/taover/repository/autoconfigure/ShardingSphereKeyGeneratorConfiguration.java | 31 ------------------------------- src/main/java/com/taover/repository/autoconfigure/TaoverRepositoryAutoConfiguration.java | 55 ------------------------------------------------------- src/main/java/com/taover/repository/bean/TenantIdentity.java | 6 ------ src/main/java/com/taover/repository/exception/NoContainTenantException.java | 16 +++++++++++++++- src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateBroadcast.java | 976 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateBroadcastImpl.java | 667 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateWrapperTenant.java | 293 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateWrapperTenantImpl.java | 644 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/taover/repository/mapper/CustomJdbcTemplateRowMapper.java | 49 ++----------------------------------------------- src/main/java/com/taover/repository/shardingsphere/ShardingDatabaseAlgorithmHint.java | 53 ----------------------------------------------------- src/main/java/com/taover/repository/shardingsphere/ShardingInfoEntity.java | 119 ----------------------------------------------------------------------------------------------------------------------- src/main/java/com/taover/repository/shardingsphere/ShardingInfoRepository.java | 11 ----------- src/main/java/com/taover/repository/shardingsphere/ShardingKeyGeneratorExt.java | 21 --------------------- src/main/java/com/taover/repository/shardingsphere/ShardingKeyGeneratorImpl.java | 217 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/taover/repository/shardingsphere/ShardingSphereService.java | 87 --------------------------------------------------------------------------------------- src/main/java/com/taover/repository/shardingsphere/ShardingTableAlgorithmHint.java | 54 ------------------------------------------------------ src/main/java/com/taover/repository/spring/autoconfigure/TaoverRepositoryAutoConfiguration.java | 24 ++++++++++++++++++++++++ src/main/resources/META-INF/services/org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator | 1 - src/main/resources/META-INF/spring.factories | 2 +- src/test/java/com/taover/repository/test/TestAutoconfigure.java | 9 ++------- src/test/java/com/taover/repository/test/TestMapper.java | 6 ++++-- src/test/java/com/taover/repository/test/repository/CommonRegionRepository.java | 9 ++++----- src/test/resources/META-INF/services/org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator | 1 - src/test/resources/META-INF/spring.factories | 2 +- src/test/resources/application.properties | 63 ++++++++++----------------------------------------------------- 31 files changed, 293 insertions(+), 4833 deletions(-) delete mode 100644 src/main/java/com/taover/repository/CustomJdbcTemplate.java delete mode 100644 src/main/java/com/taover/repository/CustomJdbcTemplateBroadcast.java delete mode 100644 src/main/java/com/taover/repository/CustomJdbcTemplateBroadcastInterface.java delete mode 100644 src/main/java/com/taover/repository/advice/EntityPointCut.java delete mode 100644 src/main/java/com/taover/repository/autoconfigure/ShardingSphereKeyGeneratorConfiguration.java delete mode 100644 src/main/java/com/taover/repository/autoconfigure/TaoverRepositoryAutoConfiguration.java delete mode 100644 src/main/java/com/taover/repository/bean/TenantIdentity.java delete mode 100644 src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateBroadcast.java delete mode 100644 src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateBroadcastImpl.java delete mode 100644 src/main/java/com/taover/repository/shardingsphere/ShardingDatabaseAlgorithmHint.java delete mode 100644 src/main/java/com/taover/repository/shardingsphere/ShardingInfoEntity.java delete mode 100644 src/main/java/com/taover/repository/shardingsphere/ShardingInfoRepository.java delete mode 100644 src/main/java/com/taover/repository/shardingsphere/ShardingKeyGeneratorExt.java delete mode 100644 src/main/java/com/taover/repository/shardingsphere/ShardingKeyGeneratorImpl.java delete mode 100644 src/main/java/com/taover/repository/shardingsphere/ShardingSphereService.java delete mode 100644 src/main/java/com/taover/repository/shardingsphere/ShardingTableAlgorithmHint.java create mode 100644 src/main/java/com/taover/repository/spring/autoconfigure/TaoverRepositoryAutoConfiguration.java delete mode 100644 src/main/resources/META-INF/services/org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator delete mode 100644 src/test/resources/META-INF/services/org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator diff --git a/build.gradle b/build.gradle index 66c687c..4b4b56e 100644 --- a/build.gradle +++ b/build.gradle @@ -21,9 +21,7 @@ dependencies { compile("org.springframework.boot:spring-boot-starter:2.0.5.RELEASE") compile("org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final") compile('org.springframework:spring-jdbc:5.1.9.RELEASE') - compile('com.alibaba:druid:1.2.4') - compile("org.apache.shardingsphere:shardingsphere-jdbc-core-spring-boot-starter:5.0.0-alpha") - compile("org.apache.shardingsphere:shardingsphere-infra-binder:6.0.0-alpha") + compile('com.alibaba:druid-spring-boot-starter:1.2.4') testCompile('mysql:mysql-connector-java:8.0.11') } @@ -58,7 +56,7 @@ uploadArchives { authentication(userName: NEXUS_USERNAME, password: NEXUS_PASSWORD) } pom.project { - version '2.2.4' + version '2.3.0' artifactId ARTIFACT_Id groupId GROUP_ID packaging TYPE diff --git a/src/main/java/com/taover/repository/CustomJdbcTemplate.java b/src/main/java/com/taover/repository/CustomJdbcTemplate.java deleted file mode 100644 index 55592a7..0000000 --- a/src/main/java/com/taover/repository/CustomJdbcTemplate.java +++ /dev/null @@ -1,929 +0,0 @@ -package com.taover.repository; - -import java.io.Serializable; -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.math.BigDecimal; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; -import javax.persistence.Column; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.springframework.dao.DataRetrievalFailureException; -import org.springframework.jdbc.core.ArgumentPreparedStatementSetter; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.core.PreparedStatementSetter; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; - -import com.taover.repository.mapper.CustomJdbcTemplateRowMapper; -import com.taover.repository.util.UtilsSql; - -/** - * - * @author root - * - * @param - * @param - */ -public class CustomJdbcTemplate { - @Resource - private JdbcTemplate jdbcTemplateRead; - @Resource - private JdbcTemplate jdbcTemplateWrite; - - private Map beanToTableField; - private Map tableToBeanField; - private String tableFieldNameListGapWithComma; - private String idTableFieldName; - private String idBeanFieldName; - private String dbName; - private String tableName; - private Class tClassInfo; - private CustomJdbcTemplateRowMapper customJdbcTemplateRowMapper; - - public CustomJdbcTemplateRowMapper getCustomJdbcTemplateRowMapper(){ - return this.customJdbcTemplateRowMapper; - } - - public CustomJdbcTemplate(JdbcTemplate jdbcTemplateWrite) throws Exception{ - this(); - this.jdbcTemplateWrite = jdbcTemplateWrite; - this.jdbcTemplateRead = jdbcTemplateWrite; - } - - public CustomJdbcTemplate() throws Exception{ - //获取泛型类Class - this.tClassInfo = (Class)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; - - //检查实体声明 - Table annoTable = (Table) tClassInfo.getAnnotation(Table.class); - if(annoTable == null){ - throw new Exception("DAO层初始化失败,失败原因:"+tClassInfo.getName()+"实体类,没有@Table注解指定表名"); - } - this.tableName = annoTable.name(); - String schema = annoTable.schema(); - String catalog = annoTable.catalog(); - if(schema != null && !"".equals(schema)){ - this.dbName = schema; - }else if(catalog != null && !"".equals(catalog)){ - this.dbName = catalog; - } - - //初始化数据 - beanToTableField = new HashMap(); - tableToBeanField = new HashMap(); - tableFieldNameListGapWithComma = ""; - Field[] declaredFields = tClassInfo.getDeclaredFields(); - for(int i=0; i - * 例如:HelloWorld->HELLO_WORLD - * @param name 转换前的驼峰式命名的字符串 - * @return 转换后下划线大写方式命名的字符串 - */ - private String camelToUnderline(String name) { - StringBuilder result = new StringBuilder(); - if (name != null && name.length() > 0) { - // 将第一个字符处理成大写 - result.append(name.substring(0, 1).toUpperCase()); - // 循环处理其余字符 - for (int i = 1; i < name.length(); i++) { - String s = name.substring(i, i + 1); - // 在大写字母前添加下划线 - if (Character.isUpperCase(s.charAt(0)) && Character.isLetter(s.charAt(0))) { - result.append("_"); - } - // 其他字符直接转成大写 - result.append(s.toUpperCase()); - } - } - return result.toString(); - } - - /** - * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。
- * 例如:HELLO_WORLD->HelloWorld - * @param name 转换前的下划线大写方式命名的字符串 - * @return 转换后的驼峰式命名的字符串 - */ - private String underlineToCamel(String name) { - StringBuilder result = new StringBuilder(); - // 快速检查 - if (name == null || name.isEmpty()) { - // 没必要转换 - return ""; - } else if (!name.contains("_")) { - // 不含下划线,仅将首字母小写 - return name.substring(0, 1).toLowerCase() + name.substring(1); - } - // 用下划线将原始字符串分割 - String camels[] = name.split("_"); - for (String camel : camels) { - // 跳过原始字符串中开头、结尾的下换线或双重下划线 - if (camel.isEmpty()) { - continue; - } - // 处理真正的驼峰片段 - if (result.length() == 0) { - // 第一个驼峰片段,全部字母都小写 - result.append(camel.toLowerCase()); - } else { - // 其他的驼峰片段,首字母大写 - result.append(camel.substring(0, 1).toUpperCase()); - result.append(camel.substring(1).toLowerCase()); - } - } - return result.toString(); - } - - private void appendWhereCondition(StringBuffer sql, StringBuffer pql, List list, List condition) { - if (condition == null || condition.size() == 0) return; - Object[] con = condition.get(0); - int iLen = condition.size(); - sql.append(" WHERE "); - pql.append(" WHERE "); - sql.append(con[0]); - pql.append(con[0]); - if (null != con[1] && con[1] != "" && con[1] != "useArg[0]") { - sql.append(" " + con[1] + " ?"); - pql.append(" " + con[1] + " " + con[2]); - list.add(con[2]); - } - for (int i = 1; i < iLen; i++) { - con = condition.get(i); - sql.append(" AND "); - pql.append(" AND "); - sql.append(con[0]); - pql.append(con[0]); - if (null == con[1] || "" == con[1] || con[1] == "useArg[0]") continue; - sql.append(" " + con[1] + " ?"); - pql.append(" " + con[1] + " " + con[2]); - list.add(con[2]); - } - } - - private void appendWhereConditionForCount(StringBuffer sql, List condition) { - if (condition == null || condition.size() == 0) return; - Object[] con = condition.get(0); - int iLen = condition.size(); - sql.append(" WHERE "); - sql.append(con[0]); - if (null != con[1] && con[1] != "" && con[1] != "useArg[0]") { - sql.append(" " + con[1] + " ?"); - } - for (int i = 1; i < iLen; i++) { - con = condition.get(i); - sql.append(" AND "); - sql.append(con[0]); - if (null == con[1] || "" == con[1] || con[1] == "useArg[0]") continue; - sql.append(" " + con[1] + " ?"); - } - } - - private void appendSetSql(StringBuffer sql, StringBuffer pql, List list, List obj) { - for (Object[] arg : obj) { - if (arg.length > 2) { - sql.append(" " + arg[0] + " = " + arg[0] + arg[2] + " ?,"); - pql.append(" " + arg[0] + " = " + arg[0] + arg[2] + arg[1] +","); - list.add(arg[1]); - }else if(arg.length == 2) { - sql.append(" " + arg[0] + " = ?,"); - pql.append(" " + arg[0] + " = " + arg[1] + ","); - list.add(arg[1]); - }else if(arg.length == 1) { - sql.append(" " + arg[0] + ","); - pql.append(" " + arg[0] + ","); - } - } - } - - private String getTableSql(){ - return (this.dbName == null || "".equals(this.dbName.trim()))? - ("`"+this.tableName+"`"): - ("`"+this.dbName+"`.`"+this.tableName+"`"); - } - - /** - * 按主键查询 - */ - public T findEntityByID(ID id) { - return findEntityByID(id, true, false); - } - - /** - * 按主键查询 - * isLock 是否锁定, 默认不锁 - * fromWriteDB 是否从写库读写,默认从读库查询 - */ - public T findEntityByID(ID id, boolean fromWriteDB, boolean isLock) { - StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); - StringBuffer pql = new StringBuffer(sql.toString()); - sql.append(" WHERE "+idTableFieldName+" = ?"); - pql.append(" WHERE "+idTableFieldName+" = " + id); - if (isLock) { - sql.append(" FOR UPDATE"); - pql.append(" FOR UPDATE"); - } - return (T) (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).queryForObject(sql.toString(), this.customJdbcTemplateRowMapper, id); - } - - /** - * 根据条件List查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public T findEntityByCondition(List condition) throws Exception { - List tempList = findListByCondition(condition, null, false); - if(tempList == null || tempList.size() == 0){ - return null; - } - if(tempList != null && tempList.size() == 1){ - return tempList.get(0); - }else{ - throw new Exception("found multi rows with condition,but this func expected one row"); - } - } - - /** - * 根据条件sql查询 - * sqlCondition 为where 后面的条件。 - */ - public T findEntityBySql(String sqlCondition) throws Exception{ - List tempList = findListBySql(sqlCondition, false); - if(tempList == null || tempList.size() == 0){ - return null; - } - if(tempList != null && tempList.size() == 1){ - return tempList.get(0); - }else{ - throw new Exception("found multi rows with condition,but this func expected one row"); - } - } - - /** - * 根据条件List查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public List findListByCondition(List condition) { - return findListByCondition(condition,null, false); - } - - /** - * 根据条件List查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public List findListByCondition(List condition, String sortCondition, boolean fromWriteDB) { - StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); - StringBuffer pql = new StringBuffer(sql.toString()); - List list = new ArrayList(); - this.appendWhereCondition(sql, pql, list, condition); - if(sortCondition != null && !sortCondition.equals("")){ - sql.append(" " + sortCondition + " "); - pql.append(" " + sortCondition + " "); - } - return (List)(fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(sql.toString(), this.customJdbcTemplateRowMapper, list.toArray()); - } - - /** - * 根据条件sql查询 - * sqlCondition 为where 后面的条件。 - */ - public List findListBySql(String sqlCondition) { - return findListBySql(sqlCondition, false); - } - - /** - * 根据条件sql查询 - * sqlCondition 为where 后面的条件。 - */ - public List findListBySql(String sqlCondition, boolean fromWriteDB) { - StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()+" WHERE " + sqlCondition); - return (List)(fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(sql.toString(), this.customJdbcTemplateRowMapper); - } - - /** - * 按条件分页查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public Map findPageByCondition(List condition,int page, int pageSize) { - return findPageByCondition(condition, null , page, pageSize, false); - } - - /** - * 按条件分页查询 - * Object[]数组长度是3 - * Object[]第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - * boolean isUseCache, 是否用缓存,默认用。 - * boolean isAddCache, 是否添加缓存,默认添加。 - */ - public Map findPageByCondition(List condition,String sortCondition, int page, int pageSize, boolean fromWriteDB) { - StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); - StringBuffer pql = new StringBuffer(sql.toString()); - StringBuffer sqlCount = new StringBuffer("SELECT COUNT(1) rowCount FROM "+this.getTableSql()); - - List count_list = new ArrayList(); - List page_list = new ArrayList(); - this.appendWhereConditionForCount(sqlCount, condition); - this.appendWhereCondition(sql, pql, count_list, condition); - for (int i = 0; i < count_list.size(); i++) - page_list.add(count_list.get(i)); - - page_list.add((page - 1) * pageSize); - page_list.add(pageSize); - - if(sortCondition != null && !sortCondition.equals("")){ - sql.append(" " + sortCondition + " "); - pql.append(" " + sortCondition + " "); - } - - String pageSql = sql.toString() + " limit ?, ?"; - - Map totalRowsMap = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).queryForMap(sqlCount.toString(), count_list.toArray()) ; - List resultList = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(pageSql.toString(), this.customJdbcTemplateRowMapper, page_list.toArray()); - return UtilsSql.createPage(page, pageSize, Integer.valueOf(totalRowsMap.get("rowCount").toString()), resultList); - } - - /** - * 按sql分页查询, sqlCondition为where 后条件sql - */ - public Map findPageBySql(String sqlCondition, int page, int pageSize) { - return findPageBySql(sqlCondition, page, pageSize, false); - } - - /** - * 按sql分页查询, sqlCondition为where 后条件sql - */ - public Map findPageBySql(String sqlCondition, int page, int pageSize,boolean fromWriteDB) { - StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()+" WHERE " + sqlCondition ); - StringBuffer sqlCount = new StringBuffer("SELECT count(1) rowCount FROM "+this.getTableSql()+" WHERE " + sqlCondition); - String pageSql = sql.toString() + " limit ?, ?"; - String pagePql = sql.toString() + " limit " + ((page -1) * pageSize) + ", " + (page * pageSize); - List page_list = new ArrayList(); - page_list.add((page - 1) * pageSize); - page_list.add(page * pageSize); - - Map totalRowsMap = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).queryForMap(sqlCount.toString()); - List resultList =(fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(pageSql.toString(), this.customJdbcTemplateRowMapper, page_list.toArray()); - return UtilsSql.createPage(page, pageSize, Integer.valueOf(totalRowsMap.get("rowCount").toString()), resultList); - } - - /** - * 添加 - */ - public Number addEntityForAutoincrementId(T entity) { - StringBuffer sqlForLog = new StringBuffer("INSERT INTO "+this.getTableSql()+"("); - StringBuffer sqlValueForLog = new StringBuffer(") VALUES ("); - StringBuffer sqlInsertPart = new StringBuffer("INSERT INTO "+this.getTableSql()+"("); - StringBuffer sqlColumnPart = new StringBuffer(") VALUES ("); - List paramList = new ArrayList(); - - Iterator beanFieldIter = this.beanToTableField.keySet().iterator(); - while(beanFieldIter.hasNext()){ - String beanFieldName = beanFieldIter.next(); - String tableFieldName = this.beanToTableField.get(beanFieldName); - Field beanField; - Object beanFieldValue = null; - try { - beanField = this.tClassInfo.getDeclaredField(beanFieldName); - beanField.setAccessible(true); - beanFieldValue = beanField.get(entity); - } catch (Exception e) { - e.printStackTrace(); - } - - if(tableFieldName == null || beanFieldName == null || beanFieldValue == null){ - continue; - } - - sqlForLog.append("`"+tableFieldName+"`,"); - sqlValueForLog.append(beanFieldValue.toString()+","); - sqlInsertPart.append("`"+tableFieldName+"`,"); - sqlColumnPart.append(" ?,"); - paramList.add(beanFieldValue); - } - //打印日志内容 - sqlForLog.substring(0, sqlForLog.length()-1); - sqlForLog.append(") VALUES ("); - sqlForLog.append(sqlValueForLog+")"); - //UtilsLog.infoForMessage(sqlForLog.toString(), this.getClass()); - - //执行SQL - String exeSql = sqlInsertPart.substring(0, sqlInsertPart.length()-1)+sqlColumnPart.substring(0, sqlColumnPart.length()-1)+")"; - KeyHolder keyHolder = new GeneratedKeyHolder(new ArrayList>(1)); - jdbcTemplateWrite.update(new PreparedStatementCreator() { - @Override - public PreparedStatement createPreparedStatement(Connection con) throws SQLException { - PreparedStatement stat = con.prepareStatement(exeSql, new String[] {idTableFieldName}); - PreparedStatementSetter setter = new ArgumentPreparedStatementSetter(paramList.toArray()); - setter.setValues(stat); - return stat; - } - - }, keyHolder); - - return keyHolder.getKey(); - } - - /** - * 批量添加 - * @throws Exception - */ - public List addEntityList(List entityList) throws Exception { - if(entityList == null || entityList.isEmpty()) { - throw new Exception("entitylist is empty or null"); - } - //构造SQL语句及Entity Field列表 - List beanFieldList = new ArrayList(this.beanToTableField.size()); - StringBuffer exeSql = new StringBuffer(this.constructUpdateSql(entityList.get(0), beanFieldList)); - - //构造参数信息 - List args = new ArrayList(); - exeSql.append(" VALUES"); - for(int itemIndex=0; itemIndex>(entityList.size())); - jdbcTemplateWrite.update(new PreparedStatementCreator() { - @Override - public PreparedStatement createPreparedStatement(Connection con) throws SQLException { - PreparedStatement stat = con.prepareStatement(exeSql.toString(), new String[] {idTableFieldName}); - PreparedStatementSetter setter = new ArgumentPreparedStatementSetter(args.toArray()); - setter.setValues(stat); - return stat; - } - - }, keyHolder); - - //处理结果数据 - List> data = keyHolder.getKeyList(); - if(data.size() != entityList.size()) { - throw new Exception("param entity size not equal return generate key list size"); - } - List dataT = new ArrayList(data.size()); - for(Map item: data) { - Iterator keyIter = item.values().iterator(); - if (keyIter.hasNext()) { - Object key = keyIter.next(); - if (!(key instanceof Number)) { - throw new DataRetrievalFailureException( - "The generated key is not of a supported numeric type. " + - "Unable to cast [" + (key != null ? key.getClass().getName() : null) + - "] to [" + Number.class.getName() + "]"); - } - dataT.add((Number)key); - }else { - throw new DataRetrievalFailureException("Unable to retrieve the generated key. " + - "Check that the table has an identity column enabled."); - } - } - return dataT; - } - - private String constructUpdateSql(T entity, List beanFieldList) { - StringBuffer sqlInsertPart = new StringBuffer("INSERT INTO "+this.getTableSql()+"("); - Iterator beanFieldIter = this.beanToTableField.keySet().iterator(); - while(beanFieldIter.hasNext()){ - String beanFieldName = beanFieldIter.next(); - String tableFieldName = this.beanToTableField.get(beanFieldName); - Field beanField = null; - try { - beanField = this.tClassInfo.getDeclaredField(beanFieldName); - beanField.setAccessible(true); - if(beanField.get(entity) == null) { - continue; - } - } catch (Exception e) { - continue; - } - - if(tableFieldName == null || beanFieldName == null){ - continue; - } - - beanFieldList.add(beanField); - sqlInsertPart.append("`"+tableFieldName+"`,"); - } - return sqlInsertPart.substring(0, sqlInsertPart.length()-1)+")"; - } - - private Object getDefaultValueByFieldType(Field itemField) { - String simpleName = itemField.getType().getSimpleName(); - if("String".equals(simpleName)) { - return ""; - }else if("Date".equals(simpleName) || "Timestamp".equals(simpleName)) { - return "2000-01-01 00:00:00"; - }else if("BigDecimal".equals(simpleName)){ - return BigDecimal.ZERO; - }else { - return 0; - } - } - - /** - * 按ID删除 - */ - public int deleteEntityByID(ID id) { - StringBuffer sql = new StringBuffer("DELETE FROM "+this.getTableSql()+" WHERE"); - StringBuffer pql = new StringBuffer(sql.toString()); - pql.append(" "+this.idTableFieldName+" = " + id); - sql.append(" "+this.idTableFieldName+" = ?"); - return jdbcTemplateWrite.update(sql.toString(), id); - } - /** - * 删除按List条件 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public int deleteEntityByCondition(List condition) throws Exception{ - if (null == condition || condition.size() == 0) { - throw new Exception("params[condition] is empty"); - } - - List list = new ArrayList(); - StringBuffer sql = new StringBuffer("DELETE FROM "+this.getTableSql()+""); - StringBuffer pql = new StringBuffer(sql.toString()); - this.appendWhereCondition(sql, pql, list, condition); - return jdbcTemplateWrite.update( sql.toString(), list.toArray()); - } - - /** - * 删除按condition条件 - * 建议使用deleteTByCondition(List condition), 如果removeTByCondition(List condition)满足不了where条件可以使用此方法。 - * condition为where后面的条件,condition不能为空。 - */ - public int deleteEntityBySql(String sqlCondition) throws Exception{ - if("".equals(sqlCondition)) { - throw new Exception("params[sqlCondition] is empty"); - } - return jdbcTemplateWrite.update( "DELETE FROM "+this.getTableSql()+" WHERE " + sqlCondition); - } - - /** - * 根据list对象逐个删除。 - */ - public List deleteEntityList(List entityList) { - List result = new ArrayList(); - for (T entity : entityList) { - Field beanField; - Object beanFieldValue = Integer.valueOf(0); - try { - beanField = this.tClassInfo.getDeclaredField(this.idBeanFieldName); - beanField.setAccessible(true); - beanFieldValue = beanField.get(entity); - } catch (Exception e) { - e.printStackTrace(); - } - result.add(deleteEntityByID((ID)beanFieldValue)); - } - return result; - } - - /** - * 根据ID修改指定的值 - */ - public int updateEntityById(List changeList, ID id) throws Exception{ - if(null == id){ - throw new Exception("params[id] is null"); - } - if (null == changeList || changeList.size() == 0) { - throw new Exception("params[changeList] is empty"); - } - - StringBuffer sql = new StringBuffer("UPDATE "+this.getTableSql()+" SET"); - StringBuffer pql = new StringBuffer(sql.toString()); - List list = new ArrayList(); - this.appendSetSql(sql, pql, list, changeList); - - String where = " WHERE "+this.idTableFieldName+"=?"; - String updateSql = sql.substring(0, sql.length()-1)+where; - list.add(id); - return jdbcTemplateWrite.update(updateSql, list.toArray()); - } - - /** - * List updateObj 要修改成的值,数组长度为2,第一个值为列名,第二个值是要改成的值。 - * List condition 修改的条件, 数组长度是3, 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public int updateEntityByCondition(List updateObj, List condition) throws Exception{ - if (null == updateObj || updateObj.size() == 0) { - throw new Exception("params[updateObj] is empty"); - } - if (null == condition || condition.size() == 0) { - throw new Exception("params[condition] is empty"); - } - - StringBuffer sql = new StringBuffer("UPDATE "+this.getTableSql()+" SET"); - StringBuffer pql = new StringBuffer(sql.toString()); - List list = new ArrayList(); - this.appendSetSql(sql, pql, list, updateObj); - - StringBuffer where = new StringBuffer(""); - StringBuffer pwhere = new StringBuffer(""); - this.appendWhereCondition(where, pwhere, list, condition); - - String updateSql = sql.substring(0, sql.length()-1)+where.toString(); - return jdbcTemplateWrite.update(updateSql, list.toArray()); - } - - /** - * List updateObj 要修改成的值,数组长度为2,第一个值为列名,第二个值是要改成的值。 - * String sqlCondition 修改的条件。 - */ - public int updateEntityBySql(List updateObj, String sqlCondition) throws Exception{ - if (null == updateObj || updateObj.size() == 0) { - throw new Exception("params[updateObj] is empty"); - } - if ("".equals(sqlCondition)) { - throw new Exception("params[sqlCondition] is empty"); - } - - StringBuffer sql = new StringBuffer("UPDATE "+this.getTableSql()+" SET"); - StringBuffer pql = new StringBuffer(sql.toString()); - List list = new ArrayList(); - this.appendSetSql(sql, pql, list, updateObj); - - String updateSql = sql.toString().substring(0, sql.length()-1) + " WHERE "+sqlCondition; - return jdbcTemplateWrite.update(updateSql, list.toArray()); - } - - public Map getPageData(String coreSql, String orderByPartSql, Integer page, Integer pageSize){ - try { - String[] splitedSql = UtilsSql.splitCoreSql(coreSql); - return this.getPageData(splitedSql[0], splitedSql[1], orderByPartSql, page, pageSize); - }catch (Exception e) { - return UtilsSql.createPage(page, pageSize, 0, new ArrayList()); - } - } - - public Map getPageData(String selectSql, String fromAndWhereSql, String orderByPartSql, Integer page, Integer pageSize){ - //构造查询语句 - String querySql = selectSql+" "+fromAndWhereSql+" "+orderByPartSql+" "+UtilsSql.getLimitCondition(page, pageSize); - - //构造统计计数语句 - String countSql = "select count(*) rowsCount from ( select 1 "+fromAndWhereSql+" ) t "; - - //执行查询 - List> queryData = new ArrayList>(); - Map countData = new HashMap(); - queryData = this.jdbcTemplateRead.queryForList(querySql); - countData = this.jdbcTemplateRead.queryForMap(countSql); - return UtilsSql.createPage(page, pageSize, Integer.valueOf(countData.get("rowsCount").toString()), queryData); - } - - public Map getBeanPageData(String coreSql, String orderByPartSql, Integer page, Integer pageSize, Class beanClass){ - try { - String[] splitedSql = UtilsSql.splitCoreSql(coreSql); - return this.getPageData(splitedSql[0], splitedSql[1], orderByPartSql, page, pageSize, beanClass); - }catch (Exception e) { - return UtilsSql.createPage(page, pageSize, 0, new ArrayList()); - } - } - - public Map getPageData(String selectSql, String fromAndWhereSql, String orderByPartSql, Integer page, Integer pageSize, Class beanClass){ - //构造查询语句 - String querySql = selectSql+" "+fromAndWhereSql+" "+orderByPartSql+" "+UtilsSql.getLimitCondition(page, pageSize); - - //构造统计计数语句 - String countSql = "select count(*) rowsCount from ( select 1 "+fromAndWhereSql+" ) t "; - - //执行查询 - List queryData = new ArrayList(); - Map countData = new HashMap(); - queryData = this.jdbcTemplateRead.queryForList(querySql, beanClass); - countData = this.jdbcTemplateRead.queryForMap(countSql); - return UtilsSql.createPage(page, pageSize, Integer.valueOf(countData.get("rowsCount").toString()), queryData); - } - - /** - * 按主键查询 - */ - public E findBeanByID(ID id, Class beanClass) { - return findBeanByID(id, true, false, beanClass); - } - - /** - * 按主键查询 - * isLock 是否锁定, 默认不锁 - * fromWriteDB 是否从写库读写,默认从读库查询 - */ - public E findBeanByID(ID id, boolean fromWriteDB, boolean isLock, Class beanClass) { - StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); - StringBuffer pql = new StringBuffer(sql.toString()); - sql.append(" WHERE "+idTableFieldName+" = ?"); - pql.append(" WHERE "+idTableFieldName+" = " + id); - if (isLock) { - sql.append(" FOR UPDATE"); - pql.append(" FOR UPDATE"); - } - return (E) (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).queryForObject(sql.toString(), new CustomJdbcTemplateRowMapper(beanClass, this.tableToBeanField), id); - } - - /** - * 根据条件List查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public E findBeanByCondition(List condition, Class beanClass) throws Exception { - List tempList = findBeanListByCondition(condition, null, false, beanClass); - if(tempList == null || tempList.size() == 0){ - return null; - } - if(tempList != null && tempList.size() == 1){ - return tempList.get(0); - }else{ - throw new Exception("found multi rows with condition,but this func expected one row"); - } - } - - /** - * 根据条件sql查询 - * sqlCondition 为where 后面的条件。 - */ - public E findBeanBySql(String sqlCondition, Class beanClass) throws Exception{ - List tempList = findBeanListBySql(sqlCondition, false, beanClass); - if(tempList == null || tempList.size() == 0){ - return null; - } - if(tempList != null && tempList.size() == 1){ - return tempList.get(0); - }else{ - throw new Exception("found multi rows with condition,but this func expected one row"); - } - } - - /** - * 根据条件List查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public List findBeanListByCondition(List condition, Class beanClass) { - return findBeanListByCondition(condition, null, false, beanClass); - } - - /** - * 根据条件List查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public List findBeanListByCondition(List condition, String sortCondition, boolean fromWriteDB, Class beanClass) { - StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); - StringBuffer pql = new StringBuffer(sql.toString()); - List list = new ArrayList(); - this.appendWhereCondition(sql, pql, list, condition); - if(sortCondition != null && !sortCondition.equals("")){ - sql.append(" " + sortCondition + " "); - pql.append(" " + sortCondition + " "); - } - return (List)(fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(sql.toString(), new CustomJdbcTemplateRowMapper(beanClass, this.tableToBeanField), list.toArray()); - } - - /** - * 根据条件sql查询 - * sqlCondition 为where 后面的条件。 - */ - public List findBeanListBySql(String sqlCondition, Class beanClass) { - return findBeanListBySql(sqlCondition, false, beanClass); - } - - /** - * 根据条件sql查询 - * sqlCondition 为where 后面的条件。 - */ - public List findBeanListBySql(String sqlCondition, boolean fromWriteDB, Class beanClass) { - StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()+" WHERE " + sqlCondition); - return (List)(fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(sql.toString(), new CustomJdbcTemplateRowMapper(beanClass, this.tableToBeanField)); - } - - /** - * 按条件分页查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public Map findBeanPageByCondition(List condition, int page, int pageSize, Class beanClass) { - return findBeanPageByCondition(condition, null , page, pageSize, false, beanClass); - } - - /** - * 按条件分页查询 - * Object[]数组长度是3 - * Object[]第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - * boolean isUseCache, 是否用缓存,默认用。 - * boolean isAddCache, 是否添加缓存,默认添加。 - */ - public Map findBeanPageByCondition(List condition,String sortCondition, int page, int pageSize, boolean fromWriteDB, Class beanClass) { - StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); - StringBuffer pql = new StringBuffer(sql.toString()); - StringBuffer sqlCount = new StringBuffer("SELECT COUNT(1) rowCount FROM "+this.getTableSql()); - - List count_list = new ArrayList(); - List page_list = new ArrayList(); - this.appendWhereConditionForCount(sqlCount, condition); - this.appendWhereCondition(sql, pql, count_list, condition); - for (int i = 0; i < count_list.size(); i++) - page_list.add(count_list.get(i)); - - page_list.add((page - 1) * pageSize); - page_list.add(pageSize); - - if(sortCondition != null && !sortCondition.equals("")){ - sql.append(" " + sortCondition + " "); - pql.append(" " + sortCondition + " "); - } - - String pageSql = sql.toString() + " limit ?, ?"; - - Map totalRowsMap = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).queryForMap(sqlCount.toString(), count_list.toArray()) ; - List resultList = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(pageSql.toString(), new CustomJdbcTemplateRowMapper(beanClass, this.tableToBeanField), page_list.toArray()); - return UtilsSql.createPage(page, pageSize, Integer.valueOf(totalRowsMap.get("rowCount").toString()), resultList); - } - - /** - * 按sql分页查询, sqlCondition为where 后条件sql - */ - public Map findBeanPageBySql(String sqlCondition, int page, int pageSize, Class beanClass) { - return findBeanPageBySql(sqlCondition, page, pageSize, false, beanClass); - } - - /** - * 按sql分页查询, sqlCondition为where 后条件sql - */ - public Map findBeanPageBySql(String sqlCondition, int page, int pageSize,boolean fromWriteDB, Class beanClass) { - StringBuffer sql = new StringBuffer("SELECT "+this.tableFieldNameListGapWithComma+" FROM "+this.getTableSql()+" WHERE " + sqlCondition ); - StringBuffer sqlCount = new StringBuffer("SELECT count(1) rowCount FROM "+this.getTableSql()+" WHERE " + sqlCondition); - String pageSql = sql.toString() + " limit ?, ?"; - String pagePql = sql.toString() + " limit " + ((page -1) * pageSize) + ", " + (page * pageSize); - List page_list = new ArrayList(); - page_list.add((page - 1) * pageSize); - page_list.add(page * pageSize); - - Map totalRowsMap = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).queryForMap(sqlCount.toString()); - List resultList = (fromWriteDB ? jdbcTemplateWrite : jdbcTemplateRead).query(pageSql.toString(), new CustomJdbcTemplateRowMapper(beanClass, this.tableToBeanField), page_list.toArray()); - return UtilsSql.createPage(page, pageSize, Integer.valueOf(totalRowsMap.get("rowCount").toString()), resultList); - } -} diff --git a/src/main/java/com/taover/repository/CustomJdbcTemplateBroadcast.java b/src/main/java/com/taover/repository/CustomJdbcTemplateBroadcast.java deleted file mode 100644 index fbbc833..0000000 --- a/src/main/java/com/taover/repository/CustomJdbcTemplateBroadcast.java +++ /dev/null @@ -1,602 +0,0 @@ -package com.taover.repository; - -import java.io.Serializable; -import java.lang.reflect.Field; -import java.lang.reflect.ParameterizedType; -import java.math.BigDecimal; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; -import javax.persistence.Column; -import javax.persistence.Id; -import javax.persistence.Table; - -import org.springframework.dao.DataAccessException; -import org.springframework.dao.DataRetrievalFailureException; -import org.springframework.jdbc.core.ArgumentPreparedStatementSetter; -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.core.PreparedStatementSetter; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; - -import com.taover.repository.exception.MultiRowException; -import com.taover.repository.exception.NoContainTenantException; -import com.taover.repository.exception.NotFoundException; -import com.taover.repository.exception.ObjectReflectException; -import com.taover.repository.jdbctemplate.JdbcTemplateBroadcast; -import com.taover.repository.mapper.CustomJdbcTemplateRowMapper; -import com.taover.repository.util.UtilsSql; - -/** - * - * @author root - * - * @param - * @param - */ -public class CustomJdbcTemplateBroadcast implements CustomJdbcTemplateBroadcastInterface{ - @Resource - private JdbcTemplateBroadcast _jdbcTemplateBroadcast; - - private Map _beanToTableField; - private Map _tableToBeanField; - private String _tableFieldNameListGapWithComma; - private String _idTableFieldName; - private String _dbName; - private String _tableName; - private Class _tClassInfo; - private CustomJdbcTemplateRowMapper _customJdbcTemplateRowMapper; - - public CustomJdbcTemplateRowMapper getCustomJdbcTemplateRowMapper(){ - return this._customJdbcTemplateRowMapper; - } - - @SuppressWarnings("unchecked") - public CustomJdbcTemplateBroadcast() throws Exception{ - //获取泛型类Class - this._tClassInfo = (Class)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; - - //检查实体声明 - Table annoTable = (Table) _tClassInfo.getAnnotation(Table.class); - if(annoTable == null){ - throw new Exception("DAO层初始化失败,失败原因:"+_tClassInfo.getName()+"实体类,没有@Table注解指定表名"); - } - this._tableName = annoTable.name(); - String schema = annoTable.schema(); - String catalog = annoTable.catalog(); - if(schema != null && !"".equals(schema)){ - this._dbName = schema; - }else if(catalog != null && !"".equals(catalog)){ - this._dbName = catalog; - } - - //初始化数据 - _beanToTableField = new HashMap(); - _tableToBeanField = new HashMap(); - _tableFieldNameListGapWithComma = ""; - Field[] declaredFields = _tClassInfo.getDeclaredFields(); - for(int i=0; i(this._tClassInfo, this._tableToBeanField); - } - - /** - * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。
- * 例如:HelloWorld->HELLO_WORLD - * @param name 转换前的驼峰式命名的字符串 - * @return 转换后下划线大写方式命名的字符串 - */ - private String camelToUnderline(String name) { - StringBuilder result = new StringBuilder(); - if (name != null && name.length() > 0) { - // 将第一个字符处理成大写 - result.append(name.substring(0, 1).toUpperCase()); - // 循环处理其余字符 - for (int i = 1; i < name.length(); i++) { - String s = name.substring(i, i + 1); - // 在大写字母前添加下划线 - if (Character.isUpperCase(s.charAt(0)) && Character.isLetter(s.charAt(0))) { - result.append("_"); - } - // 其他字符直接转成大写 - result.append(s.toUpperCase()); - } - } - return result.toString(); - } - - private void appendWhereCondition(StringBuffer sql, StringBuffer pql, List list, List condition) { - if (condition == null || condition.size() == 0) return; - Object[] con = condition.get(0); - int iLen = condition.size(); - sql.append(" WHERE "); - pql.append(" WHERE "); - sql.append(con[0]); - pql.append(con[0]); - if (null != con[1] && con[1] != "" && con[1] != "useArg[0]") { - sql.append(" " + con[1] + " ?"); - pql.append(" " + con[1] + " " + con[2]); - list.add(con[2]); - } - for (int i = 1; i < iLen; i++) { - con = condition.get(i); - sql.append(" AND "); - pql.append(" AND "); - sql.append(con[0]); - pql.append(con[0]); - if (null == con[1] || "" == con[1] || con[1] == "useArg[0]") continue; - sql.append(" " + con[1] + " ?"); - pql.append(" " + con[1] + " " + con[2]); - list.add(con[2]); - } - } - - private void appendWhereConditionForCount(StringBuffer sql, List condition) { - if (condition == null || condition.size() == 0) return; - Object[] con = condition.get(0); - int iLen = condition.size(); - sql.append(" WHERE "); - sql.append(con[0]); - if (null != con[1] && con[1] != "" && con[1] != "useArg[0]") { - sql.append(" " + con[1] + " ?"); - } - for (int i = 1; i < iLen; i++) { - con = condition.get(i); - sql.append(" AND "); - sql.append(con[0]); - if (null == con[1] || "" == con[1] || con[1] == "useArg[0]") continue; - sql.append(" " + con[1] + " ?"); - } - } - - private void appendSetSql(StringBuffer sql, StringBuffer pql, List list, List obj) { - for (Object[] arg : obj) { - if (arg.length > 2) { - sql.append(" " + arg[0] + " = " + arg[0] + arg[2] + " ?,"); - pql.append(" " + arg[0] + " = " + arg[0] + arg[2] + arg[1] +","); - list.add(arg[1]); - }else if(arg.length == 2) { - sql.append(" " + arg[0] + " = ?,"); - pql.append(" " + arg[0] + " = " + arg[1] + ","); - list.add(arg[1]); - }else if(arg.length == 1) { - sql.append(" " + arg[0] + ","); - pql.append(" " + arg[0] + ","); - } - } - } - - private String getTableSql(){ - return (this._dbName == null || "".equals(this._dbName.trim()))? - ("`"+this._tableName+"`"): - ("`"+this._dbName+"`.`"+this._tableName+"`"); - } - - private String constructUpdateSql(T entity, List beanFieldList) { - StringBuffer sqlInsertPart = new StringBuffer("INSERT INTO "+this.getTableSql()+"("); - Iterator beanFieldIter = this._beanToTableField.keySet().iterator(); - while(beanFieldIter.hasNext()){ - String beanFieldName = beanFieldIter.next(); - String tableFieldName = this._beanToTableField.get(beanFieldName); - Field beanField = null; - try { - beanField = this._tClassInfo.getDeclaredField(beanFieldName); - beanField.setAccessible(true); - if(beanField.get(entity) == null) { - continue; - } - } catch (Exception e) { - continue; - } - - if(tableFieldName == null || beanFieldName == null){ - continue; - } - - beanFieldList.add(beanField); - sqlInsertPart.append("`"+tableFieldName+"`,"); - } - return sqlInsertPart.substring(0, sqlInsertPart.length()-1)+")"; - } - - private Object getDefaultValueByFieldType(Field itemField) { - String simpleName = itemField.getType().getSimpleName(); - if("String".equals(simpleName)) { - return ""; - }else if("Date".equals(simpleName) || "Timestamp".equals(simpleName)) { - return "2000-01-01 00:00:00"; - }else if("BigDecimal".equals(simpleName)){ - return BigDecimal.ZERO; - }else { - return 0; - } - } - - @Override - public T findEntityByID(ID id) throws NotFoundException { - return findEntityByID(id, false); - } - - @Override - public T findEntityByID(ID id, boolean isLock) throws NotFoundException { - StringBuffer sql = new StringBuffer("SELECT "+this._tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); - sql.append(" WHERE "+_idTableFieldName+" = ? "); - if (isLock) { - sql.append(" FOR UPDATE"); - } - try { - return (T) _jdbcTemplateBroadcast.queryForObject(sql.toString(), this._customJdbcTemplateRowMapper, new String[] {this._tableName}, id); - }catch (DataAccessException e) { - throw new NotFoundException(e); - } - } - - @Override - public T findEntityByCondition(List condition) throws NotFoundException, MultiRowException, NoContainTenantException { - List tempList = findListByCondition(condition); - if(tempList == null || tempList.size() == 0){ - throw new NotFoundException(); - } - if(tempList != null && tempList.size() == 1){ - return tempList.get(0); - }else{ - throw new MultiRowException(); - } - } - - @Override - public T findEntityBySql(String sqlCondition) throws NotFoundException, MultiRowException { - List tempList = findListBySql(sqlCondition); - if(tempList == null || tempList.size() == 0){ - throw new NotFoundException(); - } - if(tempList != null && tempList.size() == 1){ - return tempList.get(0); - }else{ - throw new MultiRowException(); - } - } - - @Override - public List findListByCondition(List condition){ - return findListByCondition(condition, null); - } - - @Override - public List findListByCondition(List condition, String sortCondition){ - StringBuffer sql = new StringBuffer("SELECT "+this._tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); - List list = new ArrayList(); - this.appendWhereCondition(sql, new StringBuffer(), list, condition); - if(sortCondition != null && !sortCondition.equals("")){ - sql.append(" " + sortCondition + " "); - } - return (List)_jdbcTemplateBroadcast.query(sql.toString(), this._customJdbcTemplateRowMapper, new String[] {this._tableName}, list.toArray()); - } - - @Override - public List findListBySql(String sqlCondition){ - StringBuffer sql = new StringBuffer("SELECT "+this._tableFieldNameListGapWithComma+" FROM "+this.getTableSql()+" WHERE " + sqlCondition); - return (List)_jdbcTemplateBroadcast.query(sql.toString(), this._customJdbcTemplateRowMapper, new String[] {this._tableName}); - } - - @Override - public Map findPageByCondition(List condition, int page, int pageSize){ - return findPageByCondition(condition, null , page, pageSize); - } - - @Override - public Map findPageByCondition(List condition, String sortCondition, int page, int pageSize){ - StringBuffer sql = new StringBuffer("SELECT "+this._tableFieldNameListGapWithComma+" FROM "+this.getTableSql()); - StringBuffer pql = new StringBuffer(sql.toString()); - StringBuffer sqlCount = new StringBuffer("SELECT COUNT(1) rowCount FROM "+this.getTableSql()); - List count_list = new ArrayList(); - List page_list = new ArrayList(); - this.appendWhereConditionForCount(sqlCount, condition); - this.appendWhereCondition(sql, pql, count_list, condition); - for (int i = 0; i < count_list.size(); i++) - page_list.add(count_list.get(i)); - - page_list.add((page - 1) * pageSize); - page_list.add(pageSize); - - if(sortCondition != null && !sortCondition.equals("")){ - sql.append(" " + sortCondition + " "); - pql.append(" " + sortCondition + " "); - } - - String pageSql = sql.toString() + " limit ?, ?"; - Map totalRowsMap = _jdbcTemplateBroadcast.queryForMap(sqlCount.toString(), new String[] {this._tableName}, count_list.toArray()) ; - List resultList = _jdbcTemplateBroadcast.query(pageSql.toString(), this._customJdbcTemplateRowMapper, new String[] {this._tableName}, page_list.toArray()); - return UtilsSql.createPage(page, pageSize, Integer.valueOf(totalRowsMap.get("rowCount").toString()), resultList); - } - - @Override - public Map findPageBySql(String sqlCondition, int page, int pageSize){ - StringBuffer sql = new StringBuffer("SELECT "+this._tableFieldNameListGapWithComma+" FROM "+this.getTableSql()+" WHERE " + sqlCondition); - StringBuffer sqlCount = new StringBuffer("SELECT count(1) rowCount FROM "+this.getTableSql()+" WHERE " + sqlCondition); - sql.append(" limit ?, ?"); - List page_list = new ArrayList(); - page_list.add((page - 1) * pageSize); - page_list.add(page * pageSize); - - Map totalRowsMap = _jdbcTemplateBroadcast.queryForMap(sqlCount.toString(), new String[] {this._tableName}); - List resultList = _jdbcTemplateBroadcast.query(sql.toString(), this._customJdbcTemplateRowMapper, new String[] {this._tableName}, page_list.toArray()); - return UtilsSql.createPage(page, pageSize, Integer.valueOf(totalRowsMap.get("rowCount").toString()), resultList); - } - - @Override - public Number addEntity(T entity) { - StringBuffer sqlInsertPart = new StringBuffer("INSERT INTO "+this.getTableSql()+"("); - StringBuffer sqlColumnPart = new StringBuffer(") VALUES ("); - List paramList = new ArrayList(); - - Iterator beanFieldIter = this._beanToTableField.keySet().iterator(); - while(beanFieldIter.hasNext()){ - String beanFieldName = beanFieldIter.next(); - String tableFieldName = this._beanToTableField.get(beanFieldName); - Field beanField; - Object beanFieldValue = null; - try { - beanField = this._tClassInfo.getDeclaredField(beanFieldName); - beanField.setAccessible(true); - beanFieldValue = beanField.get(entity); - } catch (Exception e) { - e.printStackTrace(); - } - - if(tableFieldName == null || beanFieldName == null || beanFieldValue == null){ - continue; - } - sqlInsertPart.append("`"+tableFieldName+"`,"); - sqlColumnPart.append(" ?,"); - paramList.add(beanFieldValue); - } - - //执行SQL - String exeSql = sqlInsertPart.substring(0, sqlInsertPart.length()-1)+sqlColumnPart.substring(0, sqlColumnPart.length()-1)+")"; - KeyHolder _keyHolder = new GeneratedKeyHolder(new ArrayList>(1)); - _jdbcTemplateBroadcast.update(new PreparedStatementCreator() { - @Override - public PreparedStatement createPreparedStatement(Connection con) throws SQLException { - PreparedStatement stat = con.prepareStatement(exeSql, new String[] {_idTableFieldName}); - PreparedStatementSetter setter = new ArgumentPreparedStatementSetter(paramList.toArray()); - setter.setValues(stat); - return stat; - } - - }, _keyHolder, new String[] {this._tableName}); - - return _keyHolder.getKey(); - } - - @Override - public List addEntityList(List entityList) throws Exception { - if(entityList == null || entityList.isEmpty()) { - return Collections.EMPTY_LIST; - } - //构造SQL语句及Entity Field列表 - List beanFieldList = new ArrayList(this._beanToTableField.size()); - StringBuffer exeSql = new StringBuffer(this.constructUpdateSql(entityList.get(0), beanFieldList)); - - //构造参数信息 - List args = new ArrayList(); - exeSql.append(" VALUES"); - for(int itemIndex=0; itemIndex>(entityList.size())); - _jdbcTemplateBroadcast.update(new PreparedStatementCreator() { - @Override - public PreparedStatement createPreparedStatement(Connection con) throws SQLException { - PreparedStatement stat = con.prepareStatement(exeSql.toString(), new String[] {_idTableFieldName}); - PreparedStatementSetter setter = new ArgumentPreparedStatementSetter(args.toArray()); - setter.setValues(stat); - return stat; - } - - }, _keyHolder, new String[] {this._tableName}); - - //处理结果数据 - List> data = _keyHolder.getKeyList(); - if(data.size() != entityList.size()) { - throw new Exception("param entity size not equal return generate key list size"); - } - List dataT = new ArrayList(data.size()); - for(Map item: data) { - Iterator keyIter = item.values().iterator(); - if (keyIter.hasNext()) { - Object key = keyIter.next(); - if (!(key instanceof Number)) { - throw new DataRetrievalFailureException( - "The generated key is not of a supported numeric type. " + - "Unable to cast [" + (key != null ? key.getClass().getName() : null) + - "] to [" + Number.class.getName() + "]"); - } - dataT.add((Number)key); - }else { - throw new DataRetrievalFailureException("Unable to retrieve the generated key. " + - "Check that the table has an identity column enabled."); - } - } - return dataT; - } - - @Override - public int deleteEntityByID(ID id) { - StringBuffer sql = new StringBuffer("DELETE FROM "+this.getTableSql()+" WHERE"); - sql.append(" "+this._idTableFieldName+" = ? "); - return _jdbcTemplateBroadcast.update(sql.toString(), new String[] {this._tableName}, id); - } - - @Override - public int deleteEntityByCondition(List condition){ - if (null == condition || condition.size() == 0) { - throw new RuntimeException("params[condition] is empty"); - } - - List list = new ArrayList(); - StringBuffer sql = new StringBuffer("DELETE FROM "+this.getTableSql()+""); - StringBuffer pql = new StringBuffer(sql.toString()); - this.appendWhereCondition(sql, pql, list, condition); - return _jdbcTemplateBroadcast.update( sql.toString(), new String[] {this._tableName}, list.toArray()); - } - - @Override - public int deleteEntityBySql(String sqlCondition){ - if("".equals(sqlCondition.trim())) { - throw new RuntimeException("params[sqlCondition] is empty"); - } - return _jdbcTemplateBroadcast.update( "DELETE FROM "+this.getTableSql()+" WHERE " + sqlCondition, new String[] {this._tableName}); - } - - @Override - public int deleteEntityList(List idList){ - StringBuffer idSb = new StringBuffer(); - for(ID id: idList) { - idSb.append(id); - } - return this.deleteEntityBySql(this._idTableFieldName + " in ("+idSb.toString().substring(0, idSb.length()-1)+") "); - } - - @Override - public int updateEntityById(List changeList, ID id) { - if(null == id){ - throw new RuntimeException("params[id] is null"); - } - if (null == changeList || changeList.size() == 0) { - throw new RuntimeException("params[changeList] is empty"); - } - - StringBuffer sql = new StringBuffer("UPDATE "+this.getTableSql()+" SET"); - StringBuffer pql = new StringBuffer(sql.toString()); - List list = new ArrayList(); - this.appendSetSql(sql, pql, list, changeList); - - String where = " WHERE "+this._idTableFieldName+"=? "; - String updateSql = sql.substring(0, sql.length()-1)+where; - list.add(id); - return _jdbcTemplateBroadcast.update(updateSql, new String[] {this._tableName}, list.toArray()); - } - - @Override - public int updateEntityByCondition(List updateObj, List condition){ - if (null == updateObj || updateObj.size() == 0) { - throw new RuntimeException("params[updateObj] is empty"); - } - if (null == condition || condition.size() == 0) { - throw new RuntimeException("params[condition] is empty"); - } - - StringBuffer sql = new StringBuffer("UPDATE "+this.getTableSql()+" SET"); - StringBuffer pql = new StringBuffer(sql.toString()); - List list = new ArrayList(); - this.appendSetSql(sql, pql, list, updateObj); - - StringBuffer where = new StringBuffer(""); - StringBuffer pwhere = new StringBuffer(""); - this.appendWhereCondition(where, pwhere, list, condition); - - String updateSql = sql.substring(0, sql.length()-1)+where.toString(); - return _jdbcTemplateBroadcast.update(updateSql, new String[] {this._tableName}, list.toArray()); - } - - @Override - public int updateEntityBySql(List updateObj, String sqlCondition){ - if (null == updateObj || updateObj.size() == 0) { - throw new RuntimeException("params[updateObj] is empty"); - } - if ("".equals(sqlCondition)) { - throw new RuntimeException("params[sqlCondition] is empty"); - } - - StringBuffer sql = new StringBuffer("UPDATE "+this.getTableSql()+" SET"); - StringBuffer pql = new StringBuffer(sql.toString()); - List list = new ArrayList(); - this.appendSetSql(sql, pql, list, updateObj); - - String updateSql = sql.toString().substring(0, sql.length()-1) + " WHERE "+sqlCondition; - return _jdbcTemplateBroadcast.update(updateSql, new String[] {this._tableName}, list.toArray()); - } - - @Override - public Map getPageData(String coreSql, String orderByPartSql, Integer page, Integer pageSize){ - String[] splitedSql = UtilsSql.splitCoreSql(coreSql); - return this.getPageData(splitedSql[0], splitedSql[1], orderByPartSql, page, pageSize); - } - - @Override - public Map getPageData(String selectSql, String fromAndWhereSql, String orderByPartSql, Integer page, Integer pageSize){ - //构造查询语句 - String querySql = selectSql+" "+fromAndWhereSql+" "+orderByPartSql+" "+UtilsSql.getLimitCondition(page, pageSize); - - //构造统计计数语句 - String countSql = "select count(*) rowsCount from ( select 1 "+fromAndWhereSql+" ) t "; - - //执行查询 - List> queryData = new ArrayList>(); - Map countData = new HashMap(); - queryData = this._jdbcTemplateBroadcast.queryForList(querySql, new String[] {this._tableName}); - countData = this._jdbcTemplateBroadcast.queryForMap(countSql, new String[] {this._tableName}); - return UtilsSql.createPage(page, pageSize, Integer.valueOf(countData.get("rowsCount").toString()), queryData); - } -} diff --git a/src/main/java/com/taover/repository/CustomJdbcTemplateBroadcastInterface.java b/src/main/java/com/taover/repository/CustomJdbcTemplateBroadcastInterface.java deleted file mode 100644 index 85bfc6a..0000000 --- a/src/main/java/com/taover/repository/CustomJdbcTemplateBroadcastInterface.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.taover.repository; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import com.taover.repository.exception.MultiRowException; -import com.taover.repository.exception.NoContainTenantException; -import com.taover.repository.exception.NotFoundException; - -public interface CustomJdbcTemplateBroadcastInterface { - - /** - * 按主键查询 - */ - public T findEntityByID(ID id) throws NotFoundException; - - /** - * 按主键查询 - * isLock 是否锁定, 默认不锁 - * fromWriteDB 是否从写库读写,默认从读库查询 - */ - public T findEntityByID(ID id, boolean isLock) throws NotFoundException; - - /** - * 根据条件List查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public T findEntityByCondition(List condition) throws NotFoundException,MultiRowException,NoContainTenantException; - - /** - * 根据条件sql查询 - * sqlCondition 为where 后面的条件。 - */ - public T findEntityBySql(String sqlCondition) throws NotFoundException,MultiRowException,NoContainTenantException; - - /** - * 根据条件List查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public List findListByCondition(List condition); - - /** - * 根据条件List查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public List findListByCondition(List condition, String sortCondition); - - /** - * 根据条件sql查询 - * sqlCondition 为where 后面的条件。 - */ - public List findListBySql(String sqlCondition); - - /** - * 按条件分页查询 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public Map findPageByCondition(List condition, int page, int pageSize); - - /** - * 按条件分页查询 - * Object[]数组长度是3 - * Object[]第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - * boolean isUseCache, 是否用缓存,默认用。 - * boolean isAddCache, 是否添加缓存,默认添加。 - */ - public Map findPageByCondition(List condition, String sortCondition, int page, int pageSize); - - /** - * 按sql分页查询, sqlCondition为where 后条件sql - */ - public Map findPageBySql(String sqlCondition, int page, int pageSize); - - /** - * 添加 - */ - public Number addEntity(T entity); - - /** - * 批量添加 - * @throws Exception - */ - public List addEntityList(List entityList) throws Exception; - - /** - * 按ID删除 - */ - public int deleteEntityByID(ID id); - - /** - * 删除按List条件 - * Object[]数组长度是3 - * Object[], 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public int deleteEntityByCondition(List condition); - - /** - * 删除按condition条件 - * 建议使用deleteTByCondition(List condition), 如果removeTByCondition(List condition)满足不了where条件可以使用此方法。 - * condition为where后面的条件,condition不能为空。 - */ - public int deleteEntityBySql(String sqlCondition); - - /** - * 根据list对象逐个删除。 - * @throws NoContainTenantException - */ - public int deleteEntityList(List idList); - - /** - * 根据ID修改指定的值 - */ - public int updateEntityById(List changeList, ID id); - - /** - * List updateObj 要修改成的值,数组长度为2,第一个值为列名,第二个值是要改成的值。 - * List condition 修改的条件, 数组长度是3, 第一个参数是列名,第二个参数是操作符,第三个参数是查询条件的值。 - */ - public int updateEntityByCondition(List updateObj, List condition); - - /** - * List updateObj 要修改成的值,数组长度为2,第一个值为列名,第二个值是要改成的值。 - * String sqlCondition 修改的条件。 - */ - public int updateEntityBySql(List updateObj, String sqlCondition); - - /** - * 获取分页数据 - * @param coreSql - * @param orderByPartSql - * @param page - * @param pageSize - * @return - */ - public Map getPageData(String coreSql, String orderByPartSql, Integer page, Integer pageSize); - - /** - * 获取分页数据 - * @param selectSql - * @param fromAndWhereSql - * @param orderByPartSql - * @param page - * @param pageSize - * @return - */ - public Map getPageData(String selectSql, String fromAndWhereSql, String orderByPartSql, Integer page, Integer pageSize); - -} diff --git a/src/main/java/com/taover/repository/CustomJdbcTemplateWrapperTenant.java b/src/main/java/com/taover/repository/CustomJdbcTemplateWrapperTenant.java index 2585fd2..37cebd3 100644 --- a/src/main/java/com/taover/repository/CustomJdbcTemplateWrapperTenant.java +++ b/src/main/java/com/taover/repository/CustomJdbcTemplateWrapperTenant.java @@ -58,6 +58,10 @@ public class CustomJdbcTemplateWrapperTenant impleme public CustomJdbcTemplateRowMapper getCustomJdbcTemplateRowMapper(){ return this._customJdbcTemplateRowMapper; } + public CustomJdbcTemplateWrapperTenant(JdbcTemplateWrapperTenant jdbcTemplate) throws Exception{ + this(); + this._jdbcTemplateWrapperTenant = jdbcTemplate; + } @SuppressWarnings("unchecked") public CustomJdbcTemplateWrapperTenant() throws Exception{ @@ -396,7 +400,7 @@ public class CustomJdbcTemplateWrapperTenant impleme //执行SQL String exeSql = sqlInsertPart.substring(0, sqlInsertPart.length()-1)+sqlColumnPart.substring(0, sqlColumnPart.length()-1)+")"; KeyHolder _keyHolder = new GeneratedKeyHolder(new ArrayList>(1)); - _jdbcTemplateWrapperTenant.update(new PreparedStatementCreator() { + _jdbcTemplateWrapperTenant.getJdbcTemplate().update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement stat = con.prepareStatement(exeSql, new String[] {_idTableFieldName}); @@ -405,7 +409,7 @@ public class CustomJdbcTemplateWrapperTenant impleme return stat; } - }, _keyHolder, tenantId); + }, _keyHolder); return _keyHolder.getKey(); } @@ -447,7 +451,7 @@ public class CustomJdbcTemplateWrapperTenant impleme //调用更新接口 KeyHolder _keyHolder = new GeneratedKeyHolder(new ArrayList>(entityList.size())); - _jdbcTemplateWrapperTenant.update(new PreparedStatementCreator() { + _jdbcTemplateWrapperTenant.getJdbcTemplate().update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement stat = con.prepareStatement(exeSql.toString(), new String[] {_idTableFieldName}); @@ -456,7 +460,7 @@ public class CustomJdbcTemplateWrapperTenant impleme return stat; } - }, _keyHolder, tenantId); + }, _keyHolder); //处理结果数据 List> data = _keyHolder.getKeyList(); diff --git a/src/main/java/com/taover/repository/advice/EntityPointCut.java b/src/main/java/com/taover/repository/advice/EntityPointCut.java deleted file mode 100644 index c57eaf7..0000000 --- a/src/main/java/com/taover/repository/advice/EntityPointCut.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.taover.repository.advice; - -public interface EntityPointCut { - - public void before(); - - public void after(); -} diff --git a/src/main/java/com/taover/repository/autoconfigure/ShardingSphereKeyGeneratorConfiguration.java b/src/main/java/com/taover/repository/autoconfigure/ShardingSphereKeyGeneratorConfiguration.java deleted file mode 100644 index c071d56..0000000 --- a/src/main/java/com/taover/repository/autoconfigure/ShardingSphereKeyGeneratorConfiguration.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.taover.repository.autoconfigure; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "taover.sharding") -public class ShardingSphereKeyGeneratorConfiguration { - private String workerId; - private String maxTolerateTimeDifferenceMilliseconds; - private String maxVibrationOffset; - - public String getWorkerId() { - return workerId; - } - public void setWorkerId(String workerId) { - this.workerId = workerId; - } - public String getMaxTolerateTimeDifferenceMilliseconds() { - return maxTolerateTimeDifferenceMilliseconds; - } - public void setMaxTolerateTimeDifferenceMilliseconds(String maxTolerateTimeDifferenceMilliseconds) { - this.maxTolerateTimeDifferenceMilliseconds = maxTolerateTimeDifferenceMilliseconds; - } - public String getMaxVibrationOffset() { - return maxVibrationOffset; - } - public void setMaxVibrationOffset(String maxVibrationOffset) { - this.maxVibrationOffset = maxVibrationOffset; - } -} diff --git a/src/main/java/com/taover/repository/autoconfigure/TaoverRepositoryAutoConfiguration.java b/src/main/java/com/taover/repository/autoconfigure/TaoverRepositoryAutoConfiguration.java deleted file mode 100644 index e4384e7..0000000 --- a/src/main/java/com/taover/repository/autoconfigure/TaoverRepositoryAutoConfiguration.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.taover.repository.autoconfigure; - -import javax.annotation.Resource; - -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.jdbc.core.JdbcTemplate; - -import com.taover.repository.jdbctemplate.JdbcTemplateBroadcast; -import com.taover.repository.jdbctemplate.JdbcTemplateBroadcastImpl; -import com.taover.repository.jdbctemplate.JdbcTemplateWrapperTenant; -import com.taover.repository.jdbctemplate.JdbcTemplateWrapperTenantImpl; -import com.taover.repository.shardingsphere.ShardingInfoRepository; -import com.taover.repository.shardingsphere.ShardingSphereService; - -@Configuration -@EnableConfigurationProperties({ShardingSphereKeyGeneratorConfiguration.class}) -@AutoConfigureAfter(JdbcTemplateAutoConfiguration.class) -@ConditionalOnProperty(prefix = "spring.shardingsphere", name = "enabled", havingValue = "true", matchIfMissing = true) -@ConditionalOnClass({ShardingSphereService.class}) -@ConditionalOnMissingBean(ShardingSphereService.class) -public class TaoverRepositoryAutoConfiguration { - @Resource - private JdbcTemplate jdbcTemplate; - @Resource - private ShardingSphereKeyGeneratorConfiguration config; - @Resource - private ShardingSphereService shardingSphereService; - - @Bean - public ShardingSphereService shardingSphereService() { - return new ShardingSphereService(config); - } - - @Bean - public ShardingInfoRepository shardingInfoRepository() throws Exception { - return new ShardingInfoRepository(); - } - - @Bean - public JdbcTemplateWrapperTenant jdbcTemplateWrapperTenant() { - return new JdbcTemplateWrapperTenantImpl(this.jdbcTemplate, this.shardingSphereService); - } - - @Bean - public JdbcTemplateBroadcast jdbcTemplateWrapperBroadcast() { - return new JdbcTemplateBroadcastImpl(this.jdbcTemplate, this.shardingSphereService); - } -} diff --git a/src/main/java/com/taover/repository/bean/TenantIdentity.java b/src/main/java/com/taover/repository/bean/TenantIdentity.java deleted file mode 100644 index 9ff5a30..0000000 --- a/src/main/java/com/taover/repository/bean/TenantIdentity.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.taover.repository.bean; - -public abstract class TenantIdentity { - public abstract Long getTenantId(); -} - diff --git a/src/main/java/com/taover/repository/exception/NoContainTenantException.java b/src/main/java/com/taover/repository/exception/NoContainTenantException.java index facd0a1..8f8621b 100644 --- a/src/main/java/com/taover/repository/exception/NoContainTenantException.java +++ b/src/main/java/com/taover/repository/exception/NoContainTenantException.java @@ -1,5 +1,19 @@ package com.taover.repository.exception; -public class NoContainTenantException extends Exception { +public class NoContainTenantException extends RuntimeException { + private static final long serialVersionUID = 1L; + private String sql; + public NoContainTenantException(String sql) { + super("sql : "+sql); + this.sql = sql; + } + + public String getSql() { + return sql; + } + + public void setSql(String sql) { + this.sql = sql; + } } diff --git a/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateBroadcast.java b/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateBroadcast.java deleted file mode 100644 index 3817372..0000000 --- a/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateBroadcast.java +++ /dev/null @@ -1,976 +0,0 @@ -package com.taover.repository.jdbctemplate; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import org.springframework.dao.DataAccessException; -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.jdbc.core.BatchPreparedStatementSetter; -import org.springframework.jdbc.core.CallableStatementCallback; -import org.springframework.jdbc.core.CallableStatementCreator; -import org.springframework.jdbc.core.ColumnMapRowMapper; -import org.springframework.jdbc.core.ConnectionCallback; -import org.springframework.jdbc.core.ParameterizedPreparedStatementSetter; -import org.springframework.jdbc.core.PreparedStatementCallback; -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.core.PreparedStatementCreatorFactory; -import org.springframework.jdbc.core.PreparedStatementSetter; -import org.springframework.jdbc.core.ResultSetExtractor; -import org.springframework.jdbc.core.RowCallbackHandler; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.SingleColumnRowMapper; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.core.SqlParameterValue; -import org.springframework.jdbc.core.SqlRowSetResultSetExtractor; -import org.springframework.jdbc.core.StatementCallback; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.jdbc.support.rowset.SqlRowSet; -import org.springframework.lang.Nullable; - -public interface JdbcTemplateBroadcast { - /** - * 加载分片信息 - * @param tenantId - */ - public void loadShardingInfo(String[] broadcastTableNames); - - /** - * 清空分片信息 - */ - public void clearShardingInfo(); - - //------------------------------------------------------------------------- - // Methods dealing with a plain java.sql.Connection - //------------------------------------------------------------------------- - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC Connection. This allows for implementing arbitrary - * data access operations, within Spring's managed JDBC environment: - * that is, participating in Spring-managed transactions and converting - * JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param action a callback object that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(ConnectionCallback action, String[] broadcastTableNames) throws DataAccessException; - - - //------------------------------------------------------------------------- - // Methods dealing with static SQL (java.sql.Statement) - //------------------------------------------------------------------------- - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC Statement. This allows for implementing arbitrary data - * access operations on a single Statement, within Spring's managed JDBC - * environment: that is, participating in Spring-managed transactions and - * converting JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param action a callback that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(StatementCallback action, String[] broadcastTableNames) throws DataAccessException; - - /** - * Issue a single SQL execute, typically a DDL statement. - * @param sql static SQL to execute - * @throws DataAccessException if there is any problem - */ - void execute(String sql, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a query given static SQL, reading the ResultSet with a - * ResultSetExtractor. - *

Uses a JDBC Statement, not a PreparedStatement. If you want to - * execute a static query with a PreparedStatement, use the overloaded - * {@code query} method with {@code null} as argument array. - * @param sql the SQL query to execute - * @param rse a callback that will extract all rows of results - * @return an arbitrary result object, as returned by the ResultSetExtractor - * @throws DataAccessException if there is any problem executing the query - * @see #query(String, Object[], ResultSetExtractor) - */ - @Nullable - T query(String sql, ResultSetExtractor rse, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a query given static SQL, reading the ResultSet on a per-row - * basis with a RowCallbackHandler. - *

Uses a JDBC Statement, not a PreparedStatement. If you want to - * execute a static query with a PreparedStatement, use the overloaded - * {@code query} method with {@code null} as argument array. - * @param sql the SQL query to execute - * @param rch a callback that will extract results, one row at a time - * @throws DataAccessException if there is any problem executing the query - * @see #query(String, Object[], RowCallbackHandler) - */ - void query(String sql, RowCallbackHandler rch, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a query given static SQL, mapping each row to a result object - * via a RowMapper. - *

Uses a JDBC Statement, not a PreparedStatement. If you want to - * execute a static query with a PreparedStatement, use the overloaded - * {@code query} method with {@code null} as argument array. - * @param sql the SQL query to execute - * @param rowMapper a callback that will map one object per row - * @return the result List, containing mapped objects - * @throws DataAccessException if there is any problem executing the query - * @see #query(String, Object[], RowMapper) - */ - List query(String sql, RowMapper rowMapper, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a query given static SQL, mapping a single result row to a - * result object via a RowMapper. - *

Uses a JDBC Statement, not a PreparedStatement. If you want to - * execute a static query with a PreparedStatement, use the overloaded - * {@link #queryForObject(String, RowMapper, Object...)} method with - * {@code null} as argument array. - * @param sql the SQL query to execute - * @param rowMapper a callback that will map one object per row - * @return the single mapped object (may be {@code null} if the given - * {@link RowMapper} returned {@code} null) - * @throws IncorrectResultSizeDataAccessException if the query does not - * return exactly one row - * @throws DataAccessException if there is any problem executing the query - * @see #queryForObject(String, Object[], RowMapper) - */ - @Nullable - T queryForObject(String sql, RowMapper rowMapper, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a query for a result object, given static SQL. - *

Uses a JDBC Statement, not a PreparedStatement. If you want to - * execute a static query with a PreparedStatement, use the overloaded - * {@link #queryForObject(String, Class, Object...)} method with - * {@code null} as argument array. - *

This method is useful for running static SQL with a known outcome. - * The query is expected to be a single row/single column query; the returned - * result will be directly mapped to the corresponding object type. - * @param sql the SQL query to execute - * @param requiredType the type that the result object is expected to match - * @return the result object of the required type, or {@code null} in case of SQL NULL - * @throws IncorrectResultSizeDataAccessException if the query does not return - * exactly one row, or does not return exactly one column in that row - * @throws DataAccessException if there is any problem executing the query - * @see #queryForObject(String, Object[], Class) - */ - @Nullable - T queryForObject(String sql, Class requiredType, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a query for a result map, given static SQL. - *

Uses a JDBC Statement, not a PreparedStatement. If you want to - * execute a static query with a PreparedStatement, use the overloaded - * {@link #queryForMap(String, Object...)} method with {@code null} - * as argument array. - *

The query is expected to be a single row query; the result row will be - * mapped to a Map (one entry for each column, using the column name as the key). - * @param sql the SQL query to execute - * @return the result Map (one entry per column, with column name as key) - * @throws IncorrectResultSizeDataAccessException if the query does not - * return exactly one row - * @throws DataAccessException if there is any problem executing the query - * @see #queryForMap(String, Object[]) - * @see ColumnMapRowMapper - */ - Map queryForMap(String sql, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a query for a result list, given static SQL. - *

Uses a JDBC Statement, not a PreparedStatement. If you want to - * execute a static query with a PreparedStatement, use the overloaded - * {@code queryForList} method with {@code null} as argument array. - *

The results will be mapped to a List (one entry for each row) of - * result objects, each of them matching the specified element type. - * @param sql the SQL query to execute - * @param elementType the required type of element in the result list - * (for example, {@code Integer.class}) - * @return a List of objects that match the specified element type - * @throws DataAccessException if there is any problem executing the query - * @see #queryForList(String, Object[], Class) - * @see SingleColumnRowMapper - */ - List queryForList(String sql, Class elementType, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a query for a result list, given static SQL. - *

Uses a JDBC Statement, not a PreparedStatement. If you want to - * execute a static query with a PreparedStatement, use the overloaded - * {@code queryForList} method with {@code null} as argument array. - *

The results will be mapped to a List (one entry for each row) of - * Maps (one entry for each column using the column name as the key). - * Each element in the list will be of the form returned by this interface's - * {@code queryForMap} methods. - * @param sql the SQL query to execute - * @return an List that contains a Map per row - * @throws DataAccessException if there is any problem executing the query - * @see #queryForList(String, Object[]) - */ - List> queryForList(String sql, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a query for a SqlRowSet, given static SQL. - *

Uses a JDBC Statement, not a PreparedStatement. If you want to - * execute a static query with a PreparedStatement, use the overloaded - * {@code queryForRowSet} method with {@code null} as argument array. - *

The results will be mapped to an SqlRowSet which holds the data in a - * disconnected fashion. This wrapper will translate any SQLExceptions thrown. - *

Note that, for the default implementation, JDBC RowSet support needs to - * be available at runtime: by default, Sun's {@code com.sun.rowset.CachedRowSetImpl} - * class is used, which is part of JDK 1.5+ and also available separately as part of - * Sun's JDBC RowSet Implementations download (rowset.jar). - * @param sql the SQL query to execute - * @return a SqlRowSet representation (possibly a wrapper around a - * {@code javax.sql.rowset.CachedRowSet}) - * @throws DataAccessException if there is any problem executing the query - * @see #queryForRowSet(String, Object[]) - * @see SqlRowSetResultSetExtractor - * @see javax.sql.rowset.CachedRowSet - */ - SqlRowSet queryForRowSet(String sql, String[] broadcastTableNames) throws DataAccessException; - - /** - * Issue a single SQL update operation (such as an insert, update or delete statement). - * @param sql static SQL to execute - * @return the number of rows affected - * @throws DataAccessException if there is any problem. - */ - int update(String sql, String[] broadcastTableNames) throws DataAccessException; - - /** - * Issue multiple SQL updates on a single JDBC Statement using batching. - *

Will fall back to separate updates on a single Statement if the JDBC - * driver does not support batch updates. - * @param sql defining an array of SQL statements that will be executed. - * @return an array of the number of rows affected by each statement - * @throws DataAccessException if there is any problem executing the batch - */ - int[] batchUpdate(String[] broadcastTableNames, String... sql) throws DataAccessException; - - - //------------------------------------------------------------------------- - // Methods dealing with prepared statements - //------------------------------------------------------------------------- - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC PreparedStatement. This allows for implementing arbitrary - * data access operations on a single Statement, within Spring's managed JDBC - * environment: that is, participating in Spring-managed transactions and - * converting JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param psc a callback that creates a PreparedStatement given a Connection - * @param action a callback that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(PreparedStatementCreator psc, PreparedStatementCallback action, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC PreparedStatement. This allows for implementing arbitrary - * data access operations on a single Statement, within Spring's managed JDBC - * environment: that is, participating in Spring-managed transactions and - * converting JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param sql the SQL to execute - * @param action a callback that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(String sql, PreparedStatementCallback action, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query using a prepared statement, reading the ResultSet with a ResultSetExtractor. - *

A PreparedStatementCreator can either be implemented directly or - * configured through a PreparedStatementCreatorFactory. - * @param psc a callback that creates a PreparedStatement given a Connection - * @param rse a callback that will extract results - * @return an arbitrary result object, as returned by the ResultSetExtractor - * @throws DataAccessException if there is any problem - * @see PreparedStatementCreatorFactory - */ - @Nullable - T query(PreparedStatementCreator psc, ResultSetExtractor rse, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query using a prepared statement, reading the ResultSet with a ResultSetExtractor. - * @param sql the SQL query to execute - * @param pss a callback that knows how to set values on the prepared statement. - * If this is {@code null}, the SQL will be assumed to contain no bind parameters. - * Even if there are no bind parameters, this callback may be used to set the - * fetch size and other performance options. - * @param rse a callback that will extract results - * @return an arbitrary result object, as returned by the ResultSetExtractor - * @throws DataAccessException if there is any problem - */ - @Nullable - T query(String sql, @Nullable PreparedStatementSetter pss, ResultSetExtractor rse, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of arguments - * to bind to the query, reading the ResultSet with a ResultSetExtractor. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @param rse a callback that will extract results - * @return an arbitrary result object, as returned by the ResultSetExtractor - * @throws DataAccessException if the query fails - * @see java.sql.Types - */ - @Nullable - T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of arguments - * to bind to the query, reading the ResultSet with a ResultSetExtractor. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @param rse a callback that will extract results - * @return an arbitrary result object, as returned by the ResultSetExtractor - * @throws DataAccessException if the query fails - */ - @Nullable - T query(String sql, Object[] args, ResultSetExtractor rse, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of arguments - * to bind to the query, reading the ResultSet with a ResultSetExtractor. - * @param sql the SQL query to execute - * @param rse a callback that will extract results - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @return an arbitrary result object, as returned by the ResultSetExtractor - * @throws DataAccessException if the query fails - * @since 3.0.1 - */ - @Nullable - T query(String sql, ResultSetExtractor rse, String[] broadcastTableNames, @Nullable Object... args) throws DataAccessException; - - /** - * Query using a prepared statement, reading the ResultSet on a per-row basis - * with a RowCallbackHandler. - *

A PreparedStatementCreator can either be implemented directly or - * configured through a PreparedStatementCreatorFactory. - * @param psc a callback that creates a PreparedStatement given a Connection - * @param rch a callback that will extract results, one row at a time - * @throws DataAccessException if there is any problem - * @see PreparedStatementCreatorFactory - */ - void query(PreparedStatementCreator psc, RowCallbackHandler rch, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a - * PreparedStatementSetter implementation that knows how to bind values to the - * query, reading the ResultSet on a per-row basis with a RowCallbackHandler. - * @param sql the SQL query to execute - * @param pss a callback that knows how to set values on the prepared statement. - * If this is {@code null}, the SQL will be assumed to contain no bind parameters. - * Even if there are no bind parameters, this callback may be used to set the - * fetch size and other performance options. - * @param rch a callback that will extract results, one row at a time - * @throws DataAccessException if the query fails - */ - void query(String sql, @Nullable PreparedStatementSetter pss, RowCallbackHandler rch, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, reading the ResultSet on a per-row basis - * with a RowCallbackHandler. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @param rch a callback that will extract results, one row at a time - * @throws DataAccessException if the query fails - * @see java.sql.Types - */ - void query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, reading the ResultSet on a per-row basis - * with a RowCallbackHandler. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @param rch a callback that will extract results, one row at a time - * @throws DataAccessException if the query fails - */ - void query(String sql, Object[] args, RowCallbackHandler rch, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, reading the ResultSet on a per-row basis - * with a RowCallbackHandler. - * @param sql the SQL query to execute - * @param rch a callback that will extract results, one row at a time - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @throws DataAccessException if the query fails - * @since 3.0.1 - */ - void query(String sql, RowCallbackHandler rch, String[] broadcastTableNames, @Nullable Object... args) throws DataAccessException; - - /** - * Query using a prepared statement, mapping each row to a result object - * via a RowMapper. - *

A PreparedStatementCreator can either be implemented directly or - * configured through a PreparedStatementCreatorFactory. - * @param psc a callback that creates a PreparedStatement given a Connection - * @param rowMapper a callback that will map one object per row - * @return the result List, containing mapped objects - * @throws DataAccessException if there is any problem - * @see PreparedStatementCreatorFactory - */ - List query(PreparedStatementCreator psc, RowMapper rowMapper, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a - * PreparedStatementSetter implementation that knows how to bind values - * to the query, mapping each row to a result object via a RowMapper. - * @param sql the SQL query to execute - * @param pss a callback that knows how to set values on the prepared statement. - * If this is {@code null}, the SQL will be assumed to contain no bind parameters. - * Even if there are no bind parameters, this callback may be used to set the - * fetch size and other performance options. - * @param rowMapper a callback that will map one object per row - * @return the result List, containing mapped objects - * @throws DataAccessException if the query fails - */ - List query(String sql, @Nullable PreparedStatementSetter pss, RowMapper rowMapper, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, mapping each row to a result object - * via a RowMapper. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @param rowMapper a callback that will map one object per row - * @return the result List, containing mapped objects - * @throws DataAccessException if the query fails - * @see java.sql.Types - */ - List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, mapping each row to a result object - * via a RowMapper. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @param rowMapper a callback that will map one object per row - * @return the result List, containing mapped objects - * @throws DataAccessException if the query fails - */ - List query(String sql, Object[] args, RowMapper rowMapper, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, mapping each row to a result object - * via a RowMapper. - * @param sql the SQL query to execute - * @param rowMapper a callback that will map one object per row - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @return the result List, containing mapped objects - * @throws DataAccessException if the query fails - * @since 3.0.1 - */ - List query(String sql, RowMapper rowMapper, String[] broadcastTableNames, @Nullable Object... args) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list - * of arguments to bind to the query, mapping a single result row to a - * result object via a RowMapper. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type) - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @param rowMapper a callback that will map one object per row - * @return the single mapped object (may be {@code null} if the given - * {@link RowMapper} returned {@code} null) - * @throws IncorrectResultSizeDataAccessException if the query does not - * return exactly one row - * @throws DataAccessException if the query fails - */ - @Nullable - T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, String[] broadcastTableNames) - throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list - * of arguments to bind to the query, mapping a single result row to a - * result object via a RowMapper. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @param rowMapper a callback that will map one object per row - * @return the single mapped object (may be {@code null} if the given - * {@link RowMapper} returned {@code} null) - * @throws IncorrectResultSizeDataAccessException if the query does not - * return exactly one row - * @throws DataAccessException if the query fails - */ - @Nullable - T queryForObject(String sql, Object[] args, RowMapper rowMapper, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list - * of arguments to bind to the query, mapping a single result row to a - * result object via a RowMapper. - * @param sql the SQL query to execute - * @param rowMapper a callback that will map one object per row - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @return the single mapped object (may be {@code null} if the given - * {@link RowMapper} returned {@code} null) - * @throws IncorrectResultSizeDataAccessException if the query does not - * return exactly one row - * @throws DataAccessException if the query fails - * @since 3.0.1 - */ - @Nullable - T queryForObject(String sql, RowMapper rowMapper, String[] broadcastTableNames, @Nullable Object... args) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a result object. - *

The query is expected to be a single row/single column query; the returned - * result will be directly mapped to the corresponding object type. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @param requiredType the type that the result object is expected to match - * @return the result object of the required type, or {@code null} in case of SQL NULL - * @throws IncorrectResultSizeDataAccessException if the query does not return - * exactly one row, or does not return exactly one column in that row - * @throws DataAccessException if the query fails - * @see #queryForObject(String, Class) - * @see java.sql.Types - */ - @Nullable - T queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType, String[] broadcastTableNames) - throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a result object. - *

The query is expected to be a single row/single column query; the returned - * result will be directly mapped to the corresponding object type. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @param requiredType the type that the result object is expected to match - * @return the result object of the required type, or {@code null} in case of SQL NULL - * @throws IncorrectResultSizeDataAccessException if the query does not return - * exactly one row, or does not return exactly one column in that row - * @throws DataAccessException if the query fails - * @see #queryForObject(String, Class) - */ - @Nullable - T queryForObject(String sql, Object[] args, Class requiredType, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a result object. - *

The query is expected to be a single row/single column query; the returned - * result will be directly mapped to the corresponding object type. - * @param sql the SQL query to execute - * @param requiredType the type that the result object is expected to match - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @return the result object of the required type, or {@code null} in case of SQL NULL - * @throws IncorrectResultSizeDataAccessException if the query does not return - * exactly one row, or does not return exactly one column in that row - * @throws DataAccessException if the query fails - * @since 3.0.1 - * @see #queryForObject(String, Class) - */ - @Nullable - T queryForObject(String sql, Class requiredType, String[] broadcastTableNames, @Nullable Object... args) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a result map. - *

The query is expected to be a single row query; the result row will be - * mapped to a Map (one entry for each column, using the column name as the key). - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @return the result Map (one entry per column, with column name as key) - * @throws IncorrectResultSizeDataAccessException if the query does not - * return exactly one row - * @throws DataAccessException if the query fails - * @see #queryForMap(String) - * @see ColumnMapRowMapper - * @see java.sql.Types - */ - Map queryForMap(String sql, Object[] args, int[] argTypes, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a result map. - *

The {@code queryForMap} methods defined by this interface are appropriate - * when you don't have a domain model. Otherwise, consider using one of the - * {@code queryForObject} methods. - *

The query is expected to be a single row query; the result row will be - * mapped to a Map (one entry for each column, using the column name as the key). - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @return the result Map (one entry for each column, using the - * column name as the key) - * @throws IncorrectResultSizeDataAccessException if the query does not - * return exactly one row - * @throws DataAccessException if the query fails - * @see #queryForMap(String) - * @see ColumnMapRowMapper - */ - Map queryForMap(String sql, String[] broadcastTableNames, @Nullable Object... args) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a result list. - *

The results will be mapped to a List (one entry for each row) of - * result objects, each of them matching the specified element type. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @param elementType the required type of element in the result list - * (for example, {@code Integer.class}) - * @return a List of objects that match the specified element type - * @throws DataAccessException if the query fails - * @see #queryForList(String, Class) - * @see SingleColumnRowMapper - */ - List queryForList(String sql, Object[] args, int[] argTypes, Class elementType, String[] broadcastTableNames) - throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a result list. - *

The results will be mapped to a List (one entry for each row) of - * result objects, each of them matching the specified element type. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @param elementType the required type of element in the result list - * (for example, {@code Integer.class}) - * @return a List of objects that match the specified element type - * @throws DataAccessException if the query fails - * @see #queryForList(String, Class) - * @see SingleColumnRowMapper - */ - List queryForList(String sql, Object[] args, Class elementType, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a result list. - *

The results will be mapped to a List (one entry for each row) of - * result objects, each of them matching the specified element type. - * @param sql the SQL query to execute - * @param elementType the required type of element in the result list - * (for example, {@code Integer.class}) - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @return a List of objects that match the specified element type - * @throws DataAccessException if the query fails - * @since 3.0.1 - * @see #queryForList(String, Class) - * @see SingleColumnRowMapper - */ - List queryForList(String sql, Class elementType, String[] broadcastTableNames, @Nullable Object... args) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a result list. - *

The results will be mapped to a List (one entry for each row) of - * Maps (one entry for each column, using the column name as the key). - * Each element in the list will be of the form returned by this interface's - * {@code queryForMap} methods. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @return a List that contains a Map per row - * @throws DataAccessException if the query fails - * @see #queryForList(String) - * @see java.sql.Types - */ - List> queryForList(String sql, Object[] args, int[] argTypes, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a result list. - *

The results will be mapped to a List (one entry for each row) of - * Maps (one entry for each column, using the column name as the key). - * Each element in the list will be of the form returned by this interface's - * {@code queryForMap} methods. - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @return a List that contains a Map per row - * @throws DataAccessException if the query fails - * @see #queryForList(String) - */ - List> queryForList(String sql, String[] broadcastTableNames, @Nullable Object... args) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a SqlRowSet. - *

The results will be mapped to an SqlRowSet which holds the data in a - * disconnected fashion. This wrapper will translate any SQLExceptions thrown. - *

Note that, for the default implementation, JDBC RowSet support needs to - * be available at runtime: by default, Sun's {@code com.sun.rowset.CachedRowSetImpl} - * class is used, which is part of JDK 1.5+ and also available separately as part of - * Sun's JDBC RowSet Implementations download (rowset.jar). - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @return a SqlRowSet representation (possibly a wrapper around a - * {@code javax.sql.rowset.CachedRowSet}) - * @throws DataAccessException if there is any problem executing the query - * @see #queryForRowSet(String) - * @see SqlRowSetResultSetExtractor - * @see javax.sql.rowset.CachedRowSet - * @see java.sql.Types - */ - SqlRowSet queryForRowSet(String sql, Object[] args, int[] argTypes, String[] broadcastTableNames) throws DataAccessException; - - /** - * Query given SQL to create a prepared statement from SQL and a list of - * arguments to bind to the query, expecting a SqlRowSet. - *

The results will be mapped to an SqlRowSet which holds the data in a - * disconnected fashion. This wrapper will translate any SQLExceptions thrown. - *

Note that, for the default implementation, JDBC RowSet support needs to - * be available at runtime: by default, Sun's {@code com.sun.rowset.CachedRowSetImpl} - * class is used, which is part of JDK 1.5+ and also available separately as part of - * Sun's JDBC RowSet Implementations download (rowset.jar). - * @param sql the SQL query to execute - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @return a SqlRowSet representation (possibly a wrapper around a - * {@code javax.sql.rowset.CachedRowSet}) - * @throws DataAccessException if there is any problem executing the query - * @see #queryForRowSet(String) - * @see SqlRowSetResultSetExtractor - * @see javax.sql.rowset.CachedRowSet - */ - SqlRowSet queryForRowSet(String sql, String[] broadcastTableNames, @Nullable Object... args) throws DataAccessException; - - /** - * Issue a single SQL update operation (such as an insert, update or delete - * statement) using a PreparedStatementCreator to provide SQL and any - * required parameters. - *

A PreparedStatementCreator can either be implemented directly or - * configured through a PreparedStatementCreatorFactory. - * @param psc a callback that provides SQL and any necessary parameters - * @return the number of rows affected - * @throws DataAccessException if there is any problem issuing the update - * @see PreparedStatementCreatorFactory - */ - int update(PreparedStatementCreator psc, String[] broadcastTableNames) throws DataAccessException; - - /** - * Issue an update statement using a PreparedStatementCreator to provide SQL and - * any required parameters. Generated keys will be put into the given KeyHolder. - *

Note that the given PreparedStatementCreator has to create a statement - * with activated extraction of generated keys (a JDBC 3.0 feature). This can - * either be done directly or through using a PreparedStatementCreatorFactory. - * @param psc a callback that provides SQL and any necessary parameters - * @param generatedKeyHolder a KeyHolder that will hold the generated keys - * @return the number of rows affected - * @throws DataAccessException if there is any problem issuing the update - * @see PreparedStatementCreatorFactory - * @see org.springframework.jdbc.support.GeneratedKeyHolder - */ - int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder, String[] broadcastTableNames) throws DataAccessException; - - /** - * Issue an update statement using a PreparedStatementSetter to set bind parameters, - * with given SQL. Simpler than using a PreparedStatementCreator as this method - * will create the PreparedStatement: The PreparedStatementSetter just needs to - * set parameters. - * @param sql the SQL containing bind parameters - * @param pss helper that sets bind parameters. If this is {@code null} - * we run an update with static SQL. - * @return the number of rows affected - * @throws DataAccessException if there is any problem issuing the update - */ - int update(String sql, @Nullable PreparedStatementSetter pss, String[] broadcastTableNames) throws DataAccessException; - - /** - * Issue a single SQL update operation (such as an insert, update or delete statement) - * via a prepared statement, binding the given arguments. - * @param sql the SQL containing bind parameters - * @param args arguments to bind to the query - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @return the number of rows affected - * @throws DataAccessException if there is any problem issuing the update - * @see java.sql.Types - */ - int update(String sql, Object[] args, int[] argTypes, String[] broadcastTableNames) throws DataAccessException; - - /** - * Issue a single SQL update operation (such as an insert, update or delete statement) - * via a prepared statement, binding the given arguments. - * @param sql the SQL containing bind parameters - * @param args arguments to bind to the query - * (leaving it to the PreparedStatement to guess the corresponding SQL type); - * may also contain {@link SqlParameterValue} objects which indicate not - * only the argument value but also the SQL type and optionally the scale - * @return the number of rows affected - * @throws DataAccessException if there is any problem issuing the update - */ - int update(String sql, String[] broadcastTableNames, @Nullable Object... args) throws DataAccessException; - - /** - * Issue multiple update statements on a single PreparedStatement, - * using batch updates and a BatchPreparedStatementSetter to set values. - *

Will fall back to separate updates on a single PreparedStatement - * if the JDBC driver does not support batch updates. - * @param sql defining PreparedStatement that will be reused. - * All statements in the batch will use the same SQL. - * @param pss object to set parameters on the PreparedStatement - * created by this method - * @return an array of the number of rows affected by each statement - * @throws DataAccessException if there is any problem issuing the update - */ - int[] batchUpdate(String sql, BatchPreparedStatementSetter pss, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a batch using the supplied SQL statement with the batch of supplied arguments. - * @param sql the SQL statement to execute - * @param batchArgs the List of Object arrays containing the batch of arguments for the query - * @return an array containing the numbers of rows affected by each update in the batch - */ - int[] batchUpdate(String sql, List batchArgs, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a batch using the supplied SQL statement with the batch of supplied arguments. - * @param sql the SQL statement to execute. - * @param batchArgs the List of Object arrays containing the batch of arguments for the query - * @param argTypes the SQL types of the arguments - * (constants from {@code java.sql.Types}) - * @return an array containing the numbers of rows affected by each update in the batch - */ - int[] batchUpdate(String sql, List batchArgs, int[] argTypes, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute multiple batches using the supplied SQL statement with the collect of supplied arguments. - * The arguments' values will be set using the ParameterizedPreparedStatementSetter. - * Each batch should be of size indicated in 'batchSize'. - * @param sql the SQL statement to execute. - * @param batchArgs the List of Object arrays containing the batch of arguments for the query - * @param batchSize batch size - * @param pss the ParameterizedPreparedStatementSetter to use - * @return an array containing for each batch another array containing the numbers of rows affected - * by each update in the batch - * @since 3.1 - */ - int[][] batchUpdate(String sql, Collection batchArgs, int batchSize, - ParameterizedPreparedStatementSetter pss, String[] broadcastTableNames) throws DataAccessException; - - - //------------------------------------------------------------------------- - // Methods dealing with callable statements - //------------------------------------------------------------------------- - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC CallableStatement. This allows for implementing arbitrary - * data access operations on a single Statement, within Spring's managed JDBC - * environment: that is, participating in Spring-managed transactions and - * converting JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param csc a callback that creates a CallableStatement given a Connection - * @param action a callback that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(CallableStatementCreator csc, CallableStatementCallback action, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC CallableStatement. This allows for implementing arbitrary - * data access operations on a single Statement, within Spring's managed JDBC - * environment: that is, participating in Spring-managed transactions and - * converting JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param callString the SQL call string to execute - * @param action a callback that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(String callString, CallableStatementCallback action, String[] broadcastTableNames) throws DataAccessException; - - /** - * Execute a SQL call using a CallableStatementCreator to provide SQL and - * any required parameters. - * @param csc a callback that provides SQL and any necessary parameters - * @param declaredParameters list of declared SqlParameter objects - * @return a Map of extracted out parameters - * @throws DataAccessException if there is any problem issuing the update - */ - Map call(CallableStatementCreator csc, List declaredParameters, String[] broadcastTableNames) throws DataAccessException; -} diff --git a/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateBroadcastImpl.java b/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateBroadcastImpl.java deleted file mode 100644 index d4901b2..0000000 --- a/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateBroadcastImpl.java +++ /dev/null @@ -1,667 +0,0 @@ -package com.taover.repository.jdbctemplate; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import org.apache.shardingsphere.infra.hint.HintManager; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.BatchPreparedStatementSetter; -import org.springframework.jdbc.core.CallableStatementCallback; -import org.springframework.jdbc.core.CallableStatementCreator; -import org.springframework.jdbc.core.ConnectionCallback; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.ParameterizedPreparedStatementSetter; -import org.springframework.jdbc.core.PreparedStatementCallback; -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.core.PreparedStatementSetter; -import org.springframework.jdbc.core.ResultSetExtractor; -import org.springframework.jdbc.core.RowCallbackHandler; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.core.StatementCallback; -import org.springframework.jdbc.support.KeyHolder; -import org.springframework.jdbc.support.rowset.SqlRowSet; - -import com.taover.repository.shardingsphere.ShardingInfoEntity; -import com.taover.repository.shardingsphere.ShardingSphereService; - -public class JdbcTemplateBroadcastImpl implements JdbcTemplateBroadcast { - private JdbcTemplate jdbcTemplate; - private ShardingSphereService shardingSphereService; - - public JdbcTemplateBroadcastImpl(JdbcTemplate jdbcTemplate, ShardingSphereService shardingSphereService) { - this.jdbcTemplate = jdbcTemplate; - this.shardingSphereService = shardingSphereService; - } - - @Override - public void loadShardingInfo(String[] broadcastTableNames) { - List shardingInfo = this.shardingSphereService.getShardingInfoByTableNames(broadcastTableNames); - if(shardingInfo == null || shardingInfo.isEmpty()) { - return; - } - HintManager.clear(); - HintManager instance = HintManager.getInstance(); - for(ShardingInfoEntity item: shardingInfo) { - instance.addTableShardingValue(item.getTableName(), item.getTableSuffix()); - instance.addDatabaseShardingValue(item.getTableName(), item.getDsName()); - } - } - - @Override - public void clearShardingInfo() { - HintManager.clear(); - } - - @Override - public E execute(ConnectionCallback action, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.execute(action); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E execute(StatementCallback action, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.execute(action); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public void execute(String sql, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - this.jdbcTemplate.execute(sql); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E query(String sql, ResultSetExtractor rse, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(sql, rse); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public void query(String sql, RowCallbackHandler rch, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - this.jdbcTemplate.query(sql, rch); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List query(String sql, RowMapper rowMapper, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(sql, rowMapper); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, RowMapper rowMapper, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForObject(sql, rowMapper); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, Class requiredType, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForObject(sql, requiredType); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public Map queryForMap(String sql, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForMap(sql); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List queryForList(String sql, Class elementType, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForList(sql, elementType); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List> queryForList(String sql, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForList(sql); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public SqlRowSet queryForRowSet(String sql, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForRowSet(sql); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int update(String sql, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.update(sql); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int[] batchUpdate(String[] broadcastTableNames, String... sql) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.batchUpdate(sql); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E execute(PreparedStatementCreator psc, PreparedStatementCallback action, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.execute(psc, action); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E execute(String sql, PreparedStatementCallback action, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.execute(sql, action); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E query(PreparedStatementCreator psc, ResultSetExtractor rse, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(psc, rse); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E query(String sql, PreparedStatementSetter pss, ResultSetExtractor rse, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(sql, pss, rse); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(sql, args, argTypes, rse); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E query(String sql, Object[] args, ResultSetExtractor rse, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(sql, args, rse); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E query(String sql, ResultSetExtractor rse, String[] broadcastTableNames, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(sql, rse, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public void query(PreparedStatementCreator psc, RowCallbackHandler rch, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - this.jdbcTemplate.query(psc, rch); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public void query(String sql, PreparedStatementSetter pss, RowCallbackHandler rch, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - this.jdbcTemplate.query(sql, pss, rch); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public void query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - this.jdbcTemplate.query(sql, args, argTypes, rch); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public void query(String sql, Object[] args, RowCallbackHandler rch, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - this.jdbcTemplate.query(sql, args, rch); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public void query(String sql, RowCallbackHandler rch, String[] broadcastTableNames, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - this.jdbcTemplate.query(sql, rch, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List query(PreparedStatementCreator psc, RowMapper rowMapper, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(psc, rowMapper); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(sql, pss, rowMapper); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(sql, args, argTypes, rowMapper); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List query(String sql, Object[] args, RowMapper rowMapper, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(sql, args, rowMapper); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List query(String sql, RowMapper rowMapper, String[] broadcastTableNames, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.query(sql, rowMapper, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForObject(sql, args, argTypes, rowMapper); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, Object[] args, RowMapper rowMapper, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForObject(sql, args, rowMapper); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, RowMapper rowMapper, String[] broadcastTableNames, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForObject(sql, rowMapper, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForObject(sql, args, argTypes, requiredType); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, Object[] args, Class requiredType, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForObject(sql, args, requiredType); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, Class requiredType, String[] broadcastTableNames, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForObject(sql, requiredType, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public Map queryForMap(String sql, Object[] args, int[] argTypes, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForMap(sql, args, argTypes); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public Map queryForMap(String sql, String[] broadcastTableNames, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForMap(sql, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List queryForList(String sql, Object[] args, int[] argTypes, Class elementType, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForList(sql, args, argTypes, elementType); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List queryForList(String sql, Object[] args, Class elementType, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForList(sql, args, elementType); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List queryForList(String sql, Class elementType, String[] broadcastTableNames, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForList(sql, elementType, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List> queryForList(String sql, Object[] args, int[] argTypes, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForList(sql, args, argTypes); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public List> queryForList(String sql, String[] broadcastTableNames, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForList(sql, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public SqlRowSet queryForRowSet(String sql, Object[] args, int[] argTypes, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForRowSet(sql, args, argTypes); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public SqlRowSet queryForRowSet(String sql, String[] broadcastTableNames, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.queryForRowSet(sql, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int update(PreparedStatementCreator psc, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.update(psc); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.update(psc, generatedKeyHolder); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int update(String sql, PreparedStatementSetter pss, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.update(sql, pss); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int update(String sql, Object[] args, int[] argTypes, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.update(sql, args, argTypes); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int update(String sql, String[] broadcastTableNames, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.update(sql, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int[] batchUpdate(String sql, BatchPreparedStatementSetter pss, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.batchUpdate(sql, pss); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int[] batchUpdate(String sql, List batchArgs, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.batchUpdate(sql, batchArgs); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int[] batchUpdate(String sql, List batchArgs, int[] argTypes, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.batchUpdate(sql, batchArgs); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public int[][] batchUpdate(String sql, Collection batchArgs, int batchSize, - ParameterizedPreparedStatementSetter pss, String[] broadcastTableNames) throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.batchUpdate(sql, batchArgs, batchSize, pss); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E execute(CallableStatementCreator csc, CallableStatementCallback action, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.execute(csc, action); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E execute(String callString, CallableStatementCallback action, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.execute(callString, action); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public Map call(CallableStatementCreator csc, List declaredParameters, String[] broadcastTableNames) - throws DataAccessException { - try { - this.loadShardingInfo(broadcastTableNames); - return this.jdbcTemplate.call(csc, declaredParameters); - }finally { - this.clearShardingInfo(); - } - } -} diff --git a/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateWrapperTenant.java b/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateWrapperTenant.java index 957ecc8..d569f93 100644 --- a/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateWrapperTenant.java +++ b/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateWrapperTenant.java @@ -1,5 +1,6 @@ package com.taover.repository.jdbctemplate; +import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; @@ -7,84 +8,43 @@ import java.util.Map; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.BatchPreparedStatementSetter; -import org.springframework.jdbc.core.CallableStatementCallback; -import org.springframework.jdbc.core.CallableStatementCreator; import org.springframework.jdbc.core.ColumnMapRowMapper; -import org.springframework.jdbc.core.ConnectionCallback; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ParameterizedPreparedStatementSetter; import org.springframework.jdbc.core.PreparedStatementCallback; -import org.springframework.jdbc.core.PreparedStatementCreator; -import org.springframework.jdbc.core.PreparedStatementCreatorFactory; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.SingleColumnRowMapper; -import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.SqlParameterValue; import org.springframework.jdbc.core.SqlRowSetResultSetExtractor; -import org.springframework.jdbc.core.StatementCallback; -import org.springframework.jdbc.support.KeyHolder; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.lang.Nullable; -public interface JdbcTemplateWrapperTenant { +import com.taover.repository.exception.NoContainTenantException; + +public interface JdbcTemplateWrapperTenant { /** - * 加载分片信息 - * @param tenantId + * 获取JdbcTemplate + * @return */ - public void loadShardingInfo(Long tenantId); + JdbcTemplate getJdbcTemplate(); /** - * 清空分片信息 + * 检查租户ID + * @param sql + * @param tenantId + * @throws NoContainTenantException */ - public void clearShardingInfo(); + void doCheckTenantId(String sql, ID tenantId) throws NoContainTenantException; - //------------------------------------------------------------------------- - // Methods dealing with a plain java.sql.Connection - //------------------------------------------------------------------------- - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC Connection. This allows for implementing arbitrary - * data access operations, within Spring's managed JDBC environment: - * that is, participating in Spring-managed transactions and converting - * JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param action a callback object that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(ConnectionCallback action, Long tenantId) throws DataAccessException; - - - //------------------------------------------------------------------------- - // Methods dealing with static SQL (java.sql.Statement) - //------------------------------------------------------------------------- - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC Statement. This allows for implementing arbitrary data - * access operations on a single Statement, within Spring's managed JDBC - * environment: that is, participating in Spring-managed transactions and - * converting JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param action a callback that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(StatementCallback action, Long tenantId) throws DataAccessException; - /** * Issue a single SQL execute, typically a DDL statement. * @param sql static SQL to execute * @throws DataAccessException if there is any problem */ - void execute(String sql, Long tenantId) throws DataAccessException; + void execute(String sql, ID tenantId) throws DataAccessException; /** * Execute a query given static SQL, reading the ResultSet with a @@ -99,7 +59,7 @@ public interface JdbcTemplateWrapperTenant { * @see #query(String, Object[], ResultSetExtractor) */ @Nullable - T query(String sql, ResultSetExtractor rse, Long tenantId) throws DataAccessException; + T query(String sql, ResultSetExtractor rse, ID tenantId) throws DataAccessException; /** * Execute a query given static SQL, reading the ResultSet on a per-row @@ -112,7 +72,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if there is any problem executing the query * @see #query(String, Object[], RowCallbackHandler) */ - void query(String sql, RowCallbackHandler rch, Long tenantId) throws DataAccessException; + void query(String sql, RowCallbackHandler rch, ID tenantId) throws DataAccessException; /** * Execute a query given static SQL, mapping each row to a result object @@ -126,7 +86,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if there is any problem executing the query * @see #query(String, Object[], RowMapper) */ - List query(String sql, RowMapper rowMapper, Long tenantId) throws DataAccessException; + List query(String sql, RowMapper rowMapper, ID tenantId) throws DataAccessException; /** * Execute a query given static SQL, mapping a single result row to a @@ -145,7 +105,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForObject(String, Object[], RowMapper) */ @Nullable - T queryForObject(String sql, RowMapper rowMapper, Long tenantId) throws DataAccessException; + T queryForObject(String sql, RowMapper rowMapper, ID tenantId) throws DataAccessException; /** * Execute a query for a result object, given static SQL. @@ -165,7 +125,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForObject(String, Object[], Class) */ @Nullable - T queryForObject(String sql, Class requiredType, Long tenantId) throws DataAccessException; + T queryForObject(String sql, Class requiredType, ID tenantId) throws DataAccessException; /** * Execute a query for a result map, given static SQL. @@ -183,7 +143,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForMap(String, Object[]) * @see ColumnMapRowMapper */ - Map queryForMap(String sql, Long tenantId) throws DataAccessException; + Map queryForMap(String sql, ID tenantId) throws DataAccessException; /** * Execute a query for a result list, given static SQL. @@ -200,7 +160,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForList(String, Object[], Class) * @see SingleColumnRowMapper */ - List queryForList(String sql, Class elementType, Long tenantId) throws DataAccessException; + List queryForList(String sql, Class elementType, ID tenantId) throws DataAccessException; /** * Execute a query for a result list, given static SQL. @@ -216,7 +176,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if there is any problem executing the query * @see #queryForList(String, Object[]) */ - List> queryForList(String sql, Long tenantId) throws DataAccessException; + List> queryForList(String sql, ID tenantId) throws DataAccessException; /** * Execute a query for a SqlRowSet, given static SQL. @@ -237,7 +197,7 @@ public interface JdbcTemplateWrapperTenant { * @see SqlRowSetResultSetExtractor * @see javax.sql.rowset.CachedRowSet */ - SqlRowSet queryForRowSet(String sql, Long tenantId) throws DataAccessException; + SqlRowSet queryForRowSet(String sql, ID tenantId) throws DataAccessException; /** * Issue a single SQL update operation (such as an insert, update or delete statement). @@ -245,7 +205,7 @@ public interface JdbcTemplateWrapperTenant { * @return the number of rows affected * @throws DataAccessException if there is any problem. */ - int update(String sql, Long tenantId) throws DataAccessException; + int update(String sql, ID tenantId) throws DataAccessException; /** * Issue multiple SQL updates on a single JDBC Statement using batching. @@ -255,28 +215,7 @@ public interface JdbcTemplateWrapperTenant { * @return an array of the number of rows affected by each statement * @throws DataAccessException if there is any problem executing the batch */ - int[] batchUpdate(Long tenantId, String... sql) throws DataAccessException; - - - //------------------------------------------------------------------------- - // Methods dealing with prepared statements - //------------------------------------------------------------------------- - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC PreparedStatement. This allows for implementing arbitrary - * data access operations on a single Statement, within Spring's managed JDBC - * environment: that is, participating in Spring-managed transactions and - * converting JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param psc a callback that creates a PreparedStatement given a Connection - * @param action a callback that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(PreparedStatementCreator psc, PreparedStatementCallback action, Long tenantId) throws DataAccessException; + int[] batchUpdate(ID tenantId, String... sql) throws DataAccessException; /** * Execute a JDBC data access operation, implemented as callback action @@ -292,20 +231,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if there is any problem */ @Nullable - T execute(String sql, PreparedStatementCallback action, Long tenantId) throws DataAccessException; - - /** - * Query using a prepared statement, reading the ResultSet with a ResultSetExtractor. - *

A PreparedStatementCreator can either be implemented directly or - * configured through a PreparedStatementCreatorFactory. - * @param psc a callback that creates a PreparedStatement given a Connection - * @param rse a callback that will extract results - * @return an arbitrary result object, as returned by the ResultSetExtractor - * @throws DataAccessException if there is any problem - * @see PreparedStatementCreatorFactory - */ - @Nullable - T query(PreparedStatementCreator psc, ResultSetExtractor rse, Long tenantId) throws DataAccessException; + T execute(String sql, PreparedStatementCallback action, ID tenantId) throws DataAccessException; /** * Query using a prepared statement, reading the ResultSet with a ResultSetExtractor. @@ -319,7 +245,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if there is any problem */ @Nullable - T query(String sql, @Nullable PreparedStatementSetter pss, ResultSetExtractor rse, Long tenantId) throws DataAccessException; + T query(String sql, @Nullable PreparedStatementSetter pss, ResultSetExtractor rse, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of arguments @@ -334,7 +260,7 @@ public interface JdbcTemplateWrapperTenant { * @see java.sql.Types */ @Nullable - T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse, Long tenantId) throws DataAccessException; + T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of arguments @@ -349,7 +275,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if the query fails */ @Nullable - T query(String sql, Object[] args, ResultSetExtractor rse, Long tenantId) throws DataAccessException; + T query(String sql, Object[] args, ResultSetExtractor rse, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of arguments @@ -365,19 +291,7 @@ public interface JdbcTemplateWrapperTenant { * @since 3.0.1 */ @Nullable - T query(String sql, ResultSetExtractor rse, Long tenantId, @Nullable Object... args) throws DataAccessException; - - /** - * Query using a prepared statement, reading the ResultSet on a per-row basis - * with a RowCallbackHandler. - *

A PreparedStatementCreator can either be implemented directly or - * configured through a PreparedStatementCreatorFactory. - * @param psc a callback that creates a PreparedStatement given a Connection - * @param rch a callback that will extract results, one row at a time - * @throws DataAccessException if there is any problem - * @see PreparedStatementCreatorFactory - */ - void query(PreparedStatementCreator psc, RowCallbackHandler rch, Long tenantId) throws DataAccessException; + T query(String sql, ResultSetExtractor rse, ID tenantId, @Nullable Object... args) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -391,7 +305,7 @@ public interface JdbcTemplateWrapperTenant { * @param rch a callback that will extract results, one row at a time * @throws DataAccessException if the query fails */ - void query(String sql, @Nullable PreparedStatementSetter pss, RowCallbackHandler rch, Long tenantId) throws DataAccessException; + void query(String sql, @Nullable PreparedStatementSetter pss, RowCallbackHandler rch, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -405,7 +319,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if the query fails * @see java.sql.Types */ - void query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch, Long tenantId) throws DataAccessException; + void query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -419,7 +333,7 @@ public interface JdbcTemplateWrapperTenant { * @param rch a callback that will extract results, one row at a time * @throws DataAccessException if the query fails */ - void query(String sql, Object[] args, RowCallbackHandler rch, Long tenantId) throws DataAccessException; + void query(String sql, Object[] args, RowCallbackHandler rch, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -434,20 +348,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if the query fails * @since 3.0.1 */ - void query(String sql, RowCallbackHandler rch, Long tenantId, @Nullable Object... args) throws DataAccessException; - - /** - * Query using a prepared statement, mapping each row to a result object - * via a RowMapper. - *

A PreparedStatementCreator can either be implemented directly or - * configured through a PreparedStatementCreatorFactory. - * @param psc a callback that creates a PreparedStatement given a Connection - * @param rowMapper a callback that will map one object per row - * @return the result List, containing mapped objects - * @throws DataAccessException if there is any problem - * @see PreparedStatementCreatorFactory - */ - List query(PreparedStatementCreator psc, RowMapper rowMapper, Long tenantId) throws DataAccessException; + void query(String sql, RowCallbackHandler rch, ID tenantId, @Nullable Object... args) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a @@ -462,7 +363,7 @@ public interface JdbcTemplateWrapperTenant { * @return the result List, containing mapped objects * @throws DataAccessException if the query fails */ - List query(String sql, @Nullable PreparedStatementSetter pss, RowMapper rowMapper, Long tenantId) throws DataAccessException; + List query(String sql, @Nullable PreparedStatementSetter pss, RowMapper rowMapper, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -477,7 +378,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if the query fails * @see java.sql.Types */ - List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, Long tenantId) throws DataAccessException; + List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -492,7 +393,7 @@ public interface JdbcTemplateWrapperTenant { * @return the result List, containing mapped objects * @throws DataAccessException if the query fails */ - List query(String sql, Object[] args, RowMapper rowMapper, Long tenantId) throws DataAccessException; + List query(String sql, Object[] args, RowMapper rowMapper, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -508,7 +409,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if the query fails * @since 3.0.1 */ - List query(String sql, RowMapper rowMapper, Long tenantId, @Nullable Object... args) throws DataAccessException; + List query(String sql, RowMapper rowMapper, ID tenantId, @Nullable Object... args) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list @@ -527,7 +428,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if the query fails */ @Nullable - T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, Long tenantId) + T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, ID tenantId) throws DataAccessException; /** @@ -547,7 +448,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if the query fails */ @Nullable - T queryForObject(String sql, Object[] args, RowMapper rowMapper, Long tenantId) throws DataAccessException; + T queryForObject(String sql, Object[] args, RowMapper rowMapper, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list @@ -567,7 +468,7 @@ public interface JdbcTemplateWrapperTenant { * @since 3.0.1 */ @Nullable - T queryForObject(String sql, RowMapper rowMapper, Long tenantId, @Nullable Object... args) throws DataAccessException; + T queryForObject(String sql, RowMapper rowMapper, ID tenantId, @Nullable Object... args) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -587,7 +488,7 @@ public interface JdbcTemplateWrapperTenant { * @see java.sql.Types */ @Nullable - T queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType, Long tenantId) + T queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType, ID tenantId) throws DataAccessException; /** @@ -608,7 +509,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForObject(String, Class) */ @Nullable - T queryForObject(String sql, Object[] args, Class requiredType, Long tenantId) throws DataAccessException; + T queryForObject(String sql, Object[] args, Class requiredType, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -629,7 +530,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForObject(String, Class) */ @Nullable - T queryForObject(String sql, Class requiredType, Long tenantId, @Nullable Object... args) throws DataAccessException; + T queryForObject(String sql, Class requiredType, ID tenantId, @Nullable Object... args) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -648,7 +549,7 @@ public interface JdbcTemplateWrapperTenant { * @see ColumnMapRowMapper * @see java.sql.Types */ - Map queryForMap(String sql, Object[] args, int[] argTypes, Long tenantId) throws DataAccessException; + Map queryForMap(String sql, Object[] args, int[] argTypes, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -671,7 +572,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForMap(String) * @see ColumnMapRowMapper */ - Map queryForMap(String sql, Long tenantId, @Nullable Object... args) throws DataAccessException; + Map queryForMap(String sql, ID tenantId, @Nullable Object... args) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -689,7 +590,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForList(String, Class) * @see SingleColumnRowMapper */ - List queryForList(String sql, Object[] args, int[] argTypes, Class elementType, Long tenantId) + List queryForList(String sql, Object[] args, int[] argTypes, Class elementType, ID tenantId) throws DataAccessException; /** @@ -709,7 +610,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForList(String, Class) * @see SingleColumnRowMapper */ - List queryForList(String sql, Object[] args, Class elementType, Long tenantId) throws DataAccessException; + List queryForList(String sql, Object[] args, Class elementType, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -729,7 +630,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForList(String, Class) * @see SingleColumnRowMapper */ - List queryForList(String sql, Class elementType, Long tenantId, @Nullable Object... args) throws DataAccessException; + List queryForList(String sql, Class elementType, ID tenantId, @Nullable Object... args) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -747,7 +648,7 @@ public interface JdbcTemplateWrapperTenant { * @see #queryForList(String) * @see java.sql.Types */ - List> queryForList(String sql, Object[] args, int[] argTypes, Long tenantId) throws DataAccessException; + List> queryForList(String sql, Object[] args, int[] argTypes, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -765,7 +666,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if the query fails * @see #queryForList(String) */ - List> queryForList(String sql, Long tenantId, @Nullable Object... args) throws DataAccessException; + List> queryForList(String sql, ID tenantId, @Nullable Object... args) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -788,7 +689,7 @@ public interface JdbcTemplateWrapperTenant { * @see javax.sql.rowset.CachedRowSet * @see java.sql.Types */ - SqlRowSet queryForRowSet(String sql, Object[] args, int[] argTypes, Long tenantId) throws DataAccessException; + SqlRowSet queryForRowSet(String sql, Object[] args, int[] argTypes, ID tenantId) throws DataAccessException; /** * Query given SQL to create a prepared statement from SQL and a list of @@ -811,35 +712,7 @@ public interface JdbcTemplateWrapperTenant { * @see SqlRowSetResultSetExtractor * @see javax.sql.rowset.CachedRowSet */ - SqlRowSet queryForRowSet(String sql, Long tenantId, @Nullable Object... args) throws DataAccessException; - - /** - * Issue a single SQL update operation (such as an insert, update or delete - * statement) using a PreparedStatementCreator to provide SQL and any - * required parameters. - *

A PreparedStatementCreator can either be implemented directly or - * configured through a PreparedStatementCreatorFactory. - * @param psc a callback that provides SQL and any necessary parameters - * @return the number of rows affected - * @throws DataAccessException if there is any problem issuing the update - * @see PreparedStatementCreatorFactory - */ - int update(PreparedStatementCreator psc, Long tenantId) throws DataAccessException; - - /** - * Issue an update statement using a PreparedStatementCreator to provide SQL and - * any required parameters. Generated keys will be put into the given KeyHolder. - *

Note that the given PreparedStatementCreator has to create a statement - * with activated extraction of generated keys (a JDBC 3.0 feature). This can - * either be done directly or through using a PreparedStatementCreatorFactory. - * @param psc a callback that provides SQL and any necessary parameters - * @param generatedKeyHolder a KeyHolder that will hold the generated keys - * @return the number of rows affected - * @throws DataAccessException if there is any problem issuing the update - * @see PreparedStatementCreatorFactory - * @see org.springframework.jdbc.support.GeneratedKeyHolder - */ - int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder, Long tenantId) throws DataAccessException; + SqlRowSet queryForRowSet(String sql, ID tenantId, @Nullable Object... args) throws DataAccessException; /** * Issue an update statement using a PreparedStatementSetter to set bind parameters, @@ -852,7 +725,7 @@ public interface JdbcTemplateWrapperTenant { * @return the number of rows affected * @throws DataAccessException if there is any problem issuing the update */ - int update(String sql, @Nullable PreparedStatementSetter pss, Long tenantId) throws DataAccessException; + int update(String sql, @Nullable PreparedStatementSetter pss, ID tenantId) throws DataAccessException; /** * Issue a single SQL update operation (such as an insert, update or delete statement) @@ -865,7 +738,7 @@ public interface JdbcTemplateWrapperTenant { * @throws DataAccessException if there is any problem issuing the update * @see java.sql.Types */ - int update(String sql, Object[] args, int[] argTypes, Long tenantId) throws DataAccessException; + int update(String sql, Object[] args, int[] argTypes, ID tenantId) throws DataAccessException; /** * Issue a single SQL update operation (such as an insert, update or delete statement) @@ -878,7 +751,7 @@ public interface JdbcTemplateWrapperTenant { * @return the number of rows affected * @throws DataAccessException if there is any problem issuing the update */ - int update(String sql, Long tenantId, @Nullable Object... args) throws DataAccessException; + int update(String sql, ID tenantId, @Nullable Object... args) throws DataAccessException; /** * Issue multiple update statements on a single PreparedStatement, @@ -892,7 +765,7 @@ public interface JdbcTemplateWrapperTenant { * @return an array of the number of rows affected by each statement * @throws DataAccessException if there is any problem issuing the update */ - int[] batchUpdate(String sql, BatchPreparedStatementSetter pss, Long tenantId) throws DataAccessException; + int[] batchUpdate(String sql, BatchPreparedStatementSetter pss, ID tenantId) throws DataAccessException; /** * Execute a batch using the supplied SQL statement with the batch of supplied arguments. @@ -900,7 +773,7 @@ public interface JdbcTemplateWrapperTenant { * @param batchArgs the List of Object arrays containing the batch of arguments for the query * @return an array containing the numbers of rows affected by each update in the batch */ - int[] batchUpdate(String sql, List batchArgs, Long tenantId) throws DataAccessException; + int[] batchUpdate(String sql, List batchArgs, ID tenantId) throws DataAccessException; /** * Execute a batch using the supplied SQL statement with the batch of supplied arguments. @@ -910,7 +783,7 @@ public interface JdbcTemplateWrapperTenant { * (constants from {@code java.sql.Types}) * @return an array containing the numbers of rows affected by each update in the batch */ - int[] batchUpdate(String sql, List batchArgs, int[] argTypes, Long tenantId) throws DataAccessException; + int[] batchUpdate(String sql, List batchArgs, int[] argTypes, ID tenantId) throws DataAccessException; /** * Execute multiple batches using the supplied SQL statement with the collect of supplied arguments. @@ -925,52 +798,6 @@ public interface JdbcTemplateWrapperTenant { * @since 3.1 */ int[][] batchUpdate(String sql, Collection batchArgs, int batchSize, - ParameterizedPreparedStatementSetter pss, Long tenantId) throws DataAccessException; - - - //------------------------------------------------------------------------- - // Methods dealing with callable statements - //------------------------------------------------------------------------- - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC CallableStatement. This allows for implementing arbitrary - * data access operations on a single Statement, within Spring's managed JDBC - * environment: that is, participating in Spring-managed transactions and - * converting JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param csc a callback that creates a CallableStatement given a Connection - * @param action a callback that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(CallableStatementCreator csc, CallableStatementCallback action, Long tenantId) throws DataAccessException; - - /** - * Execute a JDBC data access operation, implemented as callback action - * working on a JDBC CallableStatement. This allows for implementing arbitrary - * data access operations on a single Statement, within Spring's managed JDBC - * environment: that is, participating in Spring-managed transactions and - * converting JDBC SQLExceptions into Spring's DataAccessException hierarchy. - *

The callback action can return a result object, for example a domain - * object or a collection of domain objects. - * @param callString the SQL call string to execute - * @param action a callback that specifies the action - * @return a result object returned by the action, or {@code null} if none - * @throws DataAccessException if there is any problem - */ - @Nullable - T execute(String callString, CallableStatementCallback action, Long tenantId) throws DataAccessException; + ParameterizedPreparedStatementSetter pss, ID tenantId) throws DataAccessException; - /** - * Execute a SQL call using a CallableStatementCreator to provide SQL and - * any required parameters. - * @param csc a callback that provides SQL and any necessary parameters - * @param declaredParameters list of declared SqlParameter objects - * @return a Map of extracted out parameters - * @throws DataAccessException if there is any problem issuing the update - */ - Map call(CallableStatementCreator csc, List declaredParameters, Long tenantId) throws DataAccessException; } diff --git a/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateWrapperTenantImpl.java b/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateWrapperTenantImpl.java index 0051697..931f0e8 100644 --- a/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateWrapperTenantImpl.java +++ b/src/main/java/com/taover/repository/jdbctemplate/JdbcTemplateWrapperTenantImpl.java @@ -1,667 +1,343 @@ package com.taover.repository.jdbctemplate; +import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; -import org.apache.shardingsphere.infra.hint.HintManager; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BatchPreparedStatementSetter; -import org.springframework.jdbc.core.CallableStatementCallback; -import org.springframework.jdbc.core.CallableStatementCreator; -import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ParameterizedPreparedStatementSetter; import org.springframework.jdbc.core.PreparedStatementCallback; -import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.core.RowMapper; -import org.springframework.jdbc.core.SqlParameter; -import org.springframework.jdbc.core.StatementCallback; -import org.springframework.jdbc.support.KeyHolder; import org.springframework.jdbc.support.rowset.SqlRowSet; -import com.taover.repository.shardingsphere.ShardingInfoEntity; -import com.taover.repository.shardingsphere.ShardingSphereService; +import com.taover.repository.exception.NoContainTenantException; -public class JdbcTemplateWrapperTenantImpl implements JdbcTemplateWrapperTenant { +public class JdbcTemplateWrapperTenantImpl implements JdbcTemplateWrapperTenant { private JdbcTemplate jdbcTemplate; - private ShardingSphereService shardingSphereService; - - public JdbcTemplateWrapperTenantImpl(JdbcTemplate jdbcTemplate, ShardingSphereService shardingSphereService) { + public JdbcTemplateWrapperTenantImpl(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; - this.shardingSphereService = shardingSphereService; } - + @Override - public void loadShardingInfo(Long tenantId) { - List shardingInfo = this.shardingSphereService.getShardingInfoByTenantId(tenantId); - if(shardingInfo == null || shardingInfo.isEmpty()) { - return; - } - HintManager.clear(); - HintManager instance = HintManager.getInstance(); - for(ShardingInfoEntity item: shardingInfo) { - instance.addTableShardingValue(item.getTableName(), item.getTableSuffix()); - instance.addDatabaseShardingValue(item.getTableName(), item.getDsName()); - } + public void doCheckTenantId(String sql, ID tenantId) throws NoContainTenantException { + } @Override - public void clearShardingInfo() { - HintManager.clear(); + public JdbcTemplate getJdbcTemplate() { + return this.jdbcTemplate; } @Override - public E execute(ConnectionCallback action, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.execute(action); - }finally { - this.clearShardingInfo(); - } + public void execute(String sql, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + this.jdbcTemplate.execute(sql); } @Override - public E execute(StatementCallback action, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.execute(action); - }finally { - this.clearShardingInfo(); - } + public E query(String sql, ResultSetExtractor rse, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.query(sql, rse); } @Override - public void execute(String sql, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - this.jdbcTemplate.execute(sql); - }finally { - this.clearShardingInfo(); - } + public void query(String sql, RowCallbackHandler rch, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + this.jdbcTemplate.query(sql, rch); } @Override - public E query(String sql, ResultSetExtractor rse, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(sql, rse); - }finally { - this.clearShardingInfo(); - } + public List query(String sql, RowMapper rowMapper, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.query(sql, rowMapper); } @Override - public void query(String sql, RowCallbackHandler rch, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - this.jdbcTemplate.query(sql, rch); - }finally { - this.clearShardingInfo(); - } + public E queryForObject(String sql, RowMapper rowMapper, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForObject(sql, rowMapper); } @Override - public List query(String sql, RowMapper rowMapper, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(sql, rowMapper); - }finally { - this.clearShardingInfo(); - } + public E queryForObject(String sql, Class requiredType, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForObject(sql, requiredType); } @Override - public E queryForObject(String sql, RowMapper rowMapper, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForObject(sql, rowMapper); - }finally { - this.clearShardingInfo(); - } + public Map queryForMap(String sql, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForMap(sql); } @Override - public E queryForObject(String sql, Class requiredType, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForObject(sql, requiredType); - }finally { - this.clearShardingInfo(); - } + public List queryForList(String sql, Class elementType, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForList(sql, elementType); } @Override - public Map queryForMap(String sql, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForMap(sql); - }finally { - this.clearShardingInfo(); - } + public List> queryForList(String sql, ID tenantId) throws DataAccessException { + return this.jdbcTemplate.queryForList(sql); } @Override - public List queryForList(String sql, Class elementType, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForList(sql, elementType); - }finally { - this.clearShardingInfo(); - } + public SqlRowSet queryForRowSet(String sql, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForRowSet(sql); } @Override - public List> queryForList(String sql, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForList(sql); - }finally { - this.clearShardingInfo(); - } + public int update(String sql, ID tenantId) throws DataAccessException { + return this.jdbcTemplate.update(sql); } @Override - public SqlRowSet queryForRowSet(String sql, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForRowSet(sql); - }finally { - this.clearShardingInfo(); + public int[] batchUpdate(ID tenantId, String... sql) throws DataAccessException { + for(String item: sql) { + this.doCheckTenantId(item, tenantId); } + return this.jdbcTemplate.batchUpdate(sql); } @Override - public int update(String sql, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.update(sql); - }finally { - this.clearShardingInfo(); - } + public E execute(String sql, PreparedStatementCallback action, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.execute(sql, action); } @Override - public int[] batchUpdate(Long tenantId, String... sql) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.batchUpdate(sql); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E execute(PreparedStatementCreator psc, PreparedStatementCallback action, Long tenantId) + public E query(String sql, PreparedStatementSetter pss, ResultSetExtractor rse, ID tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.execute(psc, action); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.query(sql, pss, rse); } @Override - public E execute(String sql, PreparedStatementCallback action, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.execute(sql, action); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E query(PreparedStatementCreator psc, ResultSetExtractor rse, Long tenantId) + public E query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse, ID tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(psc, rse); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.query(sql, args, argTypes, rse); } @Override - public E query(String sql, PreparedStatementSetter pss, ResultSetExtractor rse, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(sql, pss, rse); - }finally { - this.clearShardingInfo(); - } + public E query(String sql, Object[] args, ResultSetExtractor rse, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.query(sql, args, rse); } @Override - public E query(String sql, Object[] args, int[] argTypes, ResultSetExtractor rse, Long tenantId) + public E query(String sql, ResultSetExtractor rse, ID tenantId, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(sql, args, argTypes, rse); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E query(String sql, Object[] args, ResultSetExtractor rse, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(sql, args, rse); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E query(String sql, ResultSetExtractor rse, Long tenantId, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); + + this.doCheckTenantId(sql, tenantId); return this.jdbcTemplate.query(sql, rse, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public void query(PreparedStatementCreator psc, RowCallbackHandler rch, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - this.jdbcTemplate.query(psc, rch); - }finally { - this.clearShardingInfo(); - } } @Override - public void query(String sql, PreparedStatementSetter pss, RowCallbackHandler rch, Long tenantId) + public void query(String sql, PreparedStatementSetter pss, RowCallbackHandler rch, ID tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - this.jdbcTemplate.query(sql, pss, rch); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + this.jdbcTemplate.query(sql, pss, rch); } @Override - public void query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - this.jdbcTemplate.query(sql, args, argTypes, rch); - }finally { - this.clearShardingInfo(); - } + public void query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch, ID tenantId) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + this.jdbcTemplate.query(sql, args, argTypes, rch); } @Override - public void query(String sql, Object[] args, RowCallbackHandler rch, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - this.jdbcTemplate.query(sql, args, rch); - }finally { - this.clearShardingInfo(); - } + public void query(String sql, Object[] args, RowCallbackHandler rch, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + this.jdbcTemplate.query(sql, args, rch); } @Override - public void query(String sql, RowCallbackHandler rch, Long tenantId, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - this.jdbcTemplate.query(sql, rch, args); - }finally { - this.clearShardingInfo(); - } + public void query(String sql, RowCallbackHandler rch, ID tenantId, Object... args) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + this.jdbcTemplate.query(sql, rch, args); } @Override - public List query(PreparedStatementCreator psc, RowMapper rowMapper, Long tenantId) + public List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper, ID tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(psc, rowMapper); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.query(sql, pss, rowMapper); } @Override - public List query(String sql, PreparedStatementSetter pss, RowMapper rowMapper, Long tenantId) + public List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, ID tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(sql, pss, rowMapper); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.query(sql, args, argTypes, rowMapper); } @Override - public List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, Long tenantId) + public List query(String sql, Object[] args, RowMapper rowMapper, ID tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(sql, args, argTypes, rowMapper); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.query(sql, args, rowMapper); } @Override - public List query(String sql, Object[] args, RowMapper rowMapper, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(sql, args, rowMapper); - }finally { - this.clearShardingInfo(); - } + public List query(String sql, RowMapper rowMapper, ID tenantId, Object... args) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.query(sql, rowMapper, args); } @Override - public List query(String sql, RowMapper rowMapper, Long tenantId, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.query(sql, rowMapper, args); - }finally { - this.clearShardingInfo(); - } + public E queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, ID tenantId) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForObject(sql, args, argTypes, rowMapper); } @Override - public E queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper, Long tenantId) + public E queryForObject(String sql, Object[] args, RowMapper rowMapper, ID tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForObject(sql, args, argTypes, rowMapper); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForObject(sql, args, rowMapper); } @Override - public E queryForObject(String sql, Object[] args, RowMapper rowMapper, Long tenantId) + public E queryForObject(String sql, RowMapper rowMapper, ID tenantId, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForObject(sql, args, rowMapper); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForObject(sql, rowMapper, args); } @Override - public E queryForObject(String sql, RowMapper rowMapper, Long tenantId, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForObject(sql, rowMapper, args); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForObject(sql, args, argTypes, requiredType); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, Object[] args, Class requiredType, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForObject(sql, args, requiredType); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E queryForObject(String sql, Class requiredType, Long tenantId, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForObject(sql, requiredType, args); - }finally { - this.clearShardingInfo(); - } + public E queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType, ID tenantId) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForObject(sql, args, argTypes, requiredType); } @Override - public Map queryForMap(String sql, Object[] args, int[] argTypes, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForMap(sql, args, argTypes); - }finally { - this.clearShardingInfo(); - } + public E queryForObject(String sql, Object[] args, Class requiredType, ID tenantId) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForObject(sql, args, requiredType); } @Override - public Map queryForMap(String sql, Long tenantId, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForMap(sql, args); - }finally { - this.clearShardingInfo(); - } + public E queryForObject(String sql, Class requiredType, ID tenantId, Object... args) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForObject(sql, requiredType, args); } @Override - public List queryForList(String sql, Object[] args, int[] argTypes, Class elementType, Long tenantId) + public Map queryForMap(String sql, Object[] args, int[] argTypes, ID tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForList(sql, args, argTypes, elementType); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForMap(sql, args, argTypes); } @Override - public List queryForList(String sql, Object[] args, Class elementType, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForList(sql, args, elementType); - }finally { - this.clearShardingInfo(); - } + public Map queryForMap(String sql, ID tenantId, Object... args) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForMap(sql, args); } @Override - public List queryForList(String sql, Class elementType, Long tenantId, Object... args) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForList(sql, elementType, args); - }finally { - this.clearShardingInfo(); - } + public List queryForList(String sql, Object[] args, int[] argTypes, Class elementType, ID tenantId) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForList(sql, args, argTypes, elementType); } @Override - public List> queryForList(String sql, Object[] args, int[] argTypes, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForList(sql, args, argTypes); - }finally { - this.clearShardingInfo(); - } + public List queryForList(String sql, Object[] args, Class elementType, ID tenantId) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForList(sql, args, elementType); } @Override - public List> queryForList(String sql, Long tenantId, Object... args) + public List queryForList(String sql, Class elementType, ID tenantId, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForList(sql, args); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForList(sql, elementType, args); } @Override - public SqlRowSet queryForRowSet(String sql, Object[] args, int[] argTypes, Long tenantId) + public List> queryForList(String sql, Object[] args, int[] argTypes, ID tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForRowSet(sql, args, argTypes); - }finally { - this.clearShardingInfo(); - } + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForList(sql, args, argTypes); } @Override - public SqlRowSet queryForRowSet(String sql, Long tenantId, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.queryForRowSet(sql, args); - }finally { - this.clearShardingInfo(); - } + public List> queryForList(String sql, ID tenantId, Object... args) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForList(sql, args); } @Override - public int update(PreparedStatementCreator psc, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.update(psc); - }finally { - this.clearShardingInfo(); - } + public SqlRowSet queryForRowSet(String sql, Object[] args, int[] argTypes, ID tenantId) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForRowSet(sql, args, argTypes); } @Override - public int update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.update(psc, generatedKeyHolder); - }finally { - this.clearShardingInfo(); - } + public SqlRowSet queryForRowSet(String sql, ID tenantId, Object... args) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.queryForRowSet(sql, args); } @Override - public int update(String sql, PreparedStatementSetter pss, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.update(sql, pss); - }finally { - this.clearShardingInfo(); - } + public int update(String sql, PreparedStatementSetter pss, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.update(sql, pss); } @Override - public int update(String sql, Object[] args, int[] argTypes, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.update(sql, args, argTypes); - }finally { - this.clearShardingInfo(); - } + public int update(String sql, Object[] args, int[] argTypes, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.update(sql, args, argTypes); } @Override - public int update(String sql, Long tenantId, Object... args) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.update(sql, args); - }finally { - this.clearShardingInfo(); - } + public int update(String sql, ID tenantId, Object... args) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.update(sql, args); } @Override - public int[] batchUpdate(String sql, BatchPreparedStatementSetter pss, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.batchUpdate(sql, pss); - }finally { - this.clearShardingInfo(); - } + public int[] batchUpdate(String sql, BatchPreparedStatementSetter pss, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.batchUpdate(sql, pss); } @Override - public int[] batchUpdate(String sql, List batchArgs, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.batchUpdate(sql, batchArgs); - }finally { - this.clearShardingInfo(); - } + public int[] batchUpdate(String sql, List batchArgs, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.batchUpdate(sql, batchArgs); } @Override - public int[] batchUpdate(String sql, List batchArgs, int[] argTypes, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.batchUpdate(sql, batchArgs); - }finally { - this.clearShardingInfo(); - } + public int[] batchUpdate(String sql, List batchArgs, int[] argTypes, ID tenantId) + throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.batchUpdate(sql, batchArgs); } @Override public int[][] batchUpdate(String sql, Collection batchArgs, int batchSize, - ParameterizedPreparedStatementSetter pss, Long tenantId) throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.batchUpdate(sql, batchArgs, batchSize, pss); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E execute(CallableStatementCreator csc, CallableStatementCallback action, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.execute(csc, action); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public E execute(String callString, CallableStatementCallback action, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.execute(callString, action); - }finally { - this.clearShardingInfo(); - } - } - - @Override - public Map call(CallableStatementCreator csc, List declaredParameters, Long tenantId) - throws DataAccessException { - try { - this.loadShardingInfo(tenantId); - return this.jdbcTemplate.call(csc, declaredParameters); - }finally { - this.clearShardingInfo(); - } + ParameterizedPreparedStatementSetter pss, ID tenantId) throws DataAccessException { + this.doCheckTenantId(sql, tenantId); + return this.jdbcTemplate.batchUpdate(sql, batchArgs, batchSize, pss); } } diff --git a/src/main/java/com/taover/repository/mapper/CustomJdbcTemplateRowMapper.java b/src/main/java/com/taover/repository/mapper/CustomJdbcTemplateRowMapper.java index 9614346..634e5e7 100644 --- a/src/main/java/com/taover/repository/mapper/CustomJdbcTemplateRowMapper.java +++ b/src/main/java/com/taover/repository/mapper/CustomJdbcTemplateRowMapper.java @@ -1,7 +1,6 @@ package com.taover.repository.mapper; import java.lang.reflect.Field; -import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; @@ -15,10 +14,7 @@ import org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSetMetaDat public class CustomJdbcTemplateRowMapper implements RowMapper{ Log log = LogFactory.getLog(this.getClass()); - private Map beanFielNameToField = new HashMap(); - private Method beforeMethod = null; - private Method afterMethod = null; - + private Map beanFielNameToField = new HashMap(); private Class classInfo; private Map tableToBeanMap; @@ -30,36 +26,11 @@ public class CustomJdbcTemplateRowMapper implements RowMapper{ for(Field item: fields) { try { item.setAccessible(true); - this.beanFielNameToField.put(item.getName(), item); + this.beanFielNameToField.put(item.getName(), item); }catch (Exception e) { log.error("set field accessible:"+e.getMessage()); } } - - boolean hasImplementPointCut = false; - Class[] interfaceArr = this.classInfo.getInterfaces(); - for(int i=0; i implements RowMapper{ throw new RuntimeException(e); } - if(this.beforeMethod != null){ - try{ - beforeMethod.invoke(targetObj); - }catch(Exception e){ - log.error("invoke before exception:"+e.getMessage()); - } - } - ResultSetWrappingSqlRowSetMetaData wapping = new ResultSetWrappingSqlRowSetMetaData(rs.getMetaData()); int columnCount = wapping.getColumnCount(); for (int i = 1; i<=columnCount; i++) { @@ -112,14 +75,6 @@ public class CustomJdbcTemplateRowMapper implements RowMapper{ } } - if(this.afterMethod != null){ - try { - afterMethod.invoke(targetObj); - }catch (Exception e) { - log.error("invoke after exception:"+e.getMessage()); - } - } - return targetObj; } } diff --git a/src/main/java/com/taover/repository/shardingsphere/ShardingDatabaseAlgorithmHint.java b/src/main/java/com/taover/repository/shardingsphere/ShardingDatabaseAlgorithmHint.java deleted file mode 100644 index 471a5c7..0000000 --- a/src/main/java/com/taover/repository/shardingsphere/ShardingDatabaseAlgorithmHint.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.taover.repository.shardingsphere; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm; -import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue; - -public class ShardingDatabaseAlgorithmHint implements HintShardingAlgorithm { - Log log = LogFactory.getLog(ShardingDatabaseAlgorithmHint.class); - Properties prop = null; - - public ShardingDatabaseAlgorithmHint() { } - - @Override - public Collection doSharding(Collection availableTargetNames, HintShardingValue shardingValue) { - Collection values = shardingValue.getValues(); - if(values == null || values.isEmpty()) { - String message = shardingValue.getLogicTableName()+"已启用分库分表,SQL语句请指定tenant_id 或 使用封装好的DAO层方法"; - log.error(message); - throw new RuntimeException(message); - } - Set result = new HashSet(1); - for(String item: shardingValue.getValues()) { - result.add(item); - } - return result; - } - - @Override - public String getType() { - return "DATABASE-HINT"; - } - - @Override - public Properties getProps() { - return this.prop; - } - - @Override - public void setProps(Properties props) { - this.prop = props; - } - - @Override - public void init() { - System.out.print("ShardingDatabaseAlgorithmHint:init"); - } -} diff --git a/src/main/java/com/taover/repository/shardingsphere/ShardingInfoEntity.java b/src/main/java/com/taover/repository/shardingsphere/ShardingInfoEntity.java deleted file mode 100644 index df8e682..0000000 --- a/src/main/java/com/taover/repository/shardingsphere/ShardingInfoEntity.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.taover.repository.shardingsphere; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.sql.Timestamp; -import java.util.Date; - -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Id; -import javax.persistence.Column; - -/** - * @version 1.0.0 - */ -@Entity -@Table(name="sharding_info", catalog="") -public class ShardingInfoEntity implements Serializable { - - private static final long serialVersionUID = 1L; - - - /** - * - */ - @Id - @Column(name="id") - private java.lang.Long id; - - public java.lang.Long getId(){ - return id; - } - public void setId(java.lang.Long id){ - this.id = id; - } - - /** - * 表名 - */ - @Column(name="table_name") - private java.lang.String tableName; - - public java.lang.String getTableName(){ - return tableName; - } - public void setTableName(java.lang.String tableName){ - this.tableName = tableName; - } - - /** - * 租户ID - */ - @Column(name="tenant_id") - private java.lang.Long tenantId; - - public java.lang.Long getTenantId(){ - return tenantId; - } - public void setTenantId(java.lang.Long tenantId){ - this.tenantId = tenantId; - } - - /** - * 表后缀 - */ - @Column(name="table_suffix") - private java.lang.String tableSuffix; - - public java.lang.String getTableSuffix(){ - return tableSuffix; - } - public void setTableSuffix(java.lang.String tableSuffix){ - this.tableSuffix = tableSuffix; - } - - /** - * - */ - @Column(name="create_time") - private java.sql.Timestamp createTime; - - public java.sql.Timestamp getCreateTime(){ - return createTime; - } - public void setCreateTime(java.sql.Timestamp createTime){ - this.createTime = createTime; - } - - /** - * - */ - @Column(name="update_time") - private java.sql.Timestamp updateTime; - - public java.sql.Timestamp getUpdateTime(){ - return updateTime; - } - public void setUpdateTime(java.sql.Timestamp updateTime){ - this.updateTime = updateTime; - } - - /** - * 数据库 后缀 - */ - @Column(name="ds_name") - private java.lang.String dsName; - - public java.lang.String getDsName(){ - return dsName; - } - public void setDsName(java.lang.String dsName){ - this.dsName = dsName; - } - - @Override - public String toString() { - return "ShardingInfoEntity: [id="+id+",tableName="+tableName+",tenantId="+tenantId+",tableSuffix="+tableSuffix+",createTime="+createTime+",updateTime="+updateTime+",dsName="+dsName+"]"; - } - } diff --git a/src/main/java/com/taover/repository/shardingsphere/ShardingInfoRepository.java b/src/main/java/com/taover/repository/shardingsphere/ShardingInfoRepository.java deleted file mode 100644 index 36ec381..0000000 --- a/src/main/java/com/taover/repository/shardingsphere/ShardingInfoRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.taover.repository.shardingsphere; - -import com.taover.repository.CustomJdbcTemplate; - -public class ShardingInfoRepository extends CustomJdbcTemplate{ - - public ShardingInfoRepository() throws Exception { - super(); - } - -} diff --git a/src/main/java/com/taover/repository/shardingsphere/ShardingKeyGeneratorExt.java b/src/main/java/com/taover/repository/shardingsphere/ShardingKeyGeneratorExt.java deleted file mode 100644 index a1a9778..0000000 --- a/src/main/java/com/taover/repository/shardingsphere/ShardingKeyGeneratorExt.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.taover.repository.shardingsphere; - -import java.util.List; - -import com.taover.repository.autoconfigure.ShardingSphereKeyGeneratorConfiguration; - -public interface ShardingKeyGeneratorExt { - /** - * 生成ID List - * @param shardingOffset 分片索引 - * @param genNum 生成数量 - * @return - */ - List generateKeyList(int genNum); - - /** - * 设置属性值 - * @param config - */ - void loalConfig(ShardingSphereKeyGeneratorConfiguration config); -} diff --git a/src/main/java/com/taover/repository/shardingsphere/ShardingKeyGeneratorImpl.java b/src/main/java/com/taover/repository/shardingsphere/ShardingKeyGeneratorImpl.java deleted file mode 100644 index eca78b9..0000000 --- a/src/main/java/com/taover/repository/shardingsphere/ShardingKeyGeneratorImpl.java +++ /dev/null @@ -1,217 +0,0 @@ -package com.taover.repository.shardingsphere; -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.Properties; - -import org.apache.shardingsphere.sharding.algorithm.keygen.TimeService; -import org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm; - -import com.google.common.base.Preconditions; -import com.taover.repository.autoconfigure.ShardingSphereKeyGeneratorConfiguration; - -/** - * Snowflake distributed primary key generator. - * - *

- * Use snowflake algorithm. Length is 64 bit. - *

- * - *
- * 1bit sign bit.
- * 41bits timestamp offset from 2016.11.01(ShardingSphere distributed primary key published data) to now.
- * 10bits worker process id.
- * 12bits auto increment offset in one mills
- * 
- * - *

- * Call @{@code SnowflakeShardingKeyGenerator.setWorkerId} to set worker id, default value is 0. - *

- * - *

- * Call @{@code SnowflakeShardingKeyGenerator.setMaxTolerateTimeDifferenceMilliseconds} to set max tolerate time difference milliseconds, default value is 0. - *

- */ -public final class ShardingKeyGeneratorImpl implements KeyGenerateAlgorithm, ShardingKeyGeneratorExt { - - public static final long EPOCH; - - private static final long SEQUENCE_BITS = 11L; - - private static final long BATCH_FLAG_BITS = 1L; - - private static final long WORKER_ID_BITS = 10L; - - private static final long SEQUENCE_MASK = (1 << SEQUENCE_BITS) - 1; - - private static final long BATCH_FLAG_LEFT_SHIFT_BITS = SEQUENCE_BITS; - - private static final long WORKER_ID_LEFT_SHIFT_BITS = BATCH_FLAG_LEFT_SHIFT_BITS + BATCH_FLAG_BITS; - - private static final long TIMESTAMP_LEFT_SHIFT_BITS = WORKER_ID_LEFT_SHIFT_BITS + WORKER_ID_BITS; - - private static final long WORKER_ID_MAX_VALUE = 1L << WORKER_ID_BITS; - - private static final long WORKER_ID = 0; - - private static final int DEFAULT_VIBRATION_VALUE = 1; - - private static final int MAX_TOLERATE_TIME_DIFFERENCE_MILLISECONDS = 10; - - private static TimeService timeService = new TimeService(); - - private Properties properties = new Properties(); - - private int sequenceOffset = -1; - - private long sequence; - - private long lastMilliseconds; - - static { - Calendar calendar = Calendar.getInstance(); - calendar.set(2016, Calendar.NOVEMBER, 1); - calendar.set(Calendar.HOUR_OF_DAY, 0); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MILLISECOND, 0); - EPOCH = calendar.getTimeInMillis(); - } - - @Override - public String getType() { - return "SNOWFLAKE-SELF"; - } - - @Override - public synchronized Comparable generateKey() { - long currentMilliseconds = timeService.getCurrentMillis(); - if (waitTolerateTimeDifferenceIfNeed(currentMilliseconds)) { - currentMilliseconds = timeService.getCurrentMillis(); - } - if (lastMilliseconds == currentMilliseconds) { - if (0L == (sequence = (sequence + 1) & SEQUENCE_MASK)) { - currentMilliseconds = waitUntilNextTime(currentMilliseconds); - } - } else { - vibrateSequenceOffset(); - sequence = sequenceOffset; - } - lastMilliseconds = currentMilliseconds; - return ((currentMilliseconds - EPOCH) << TIMESTAMP_LEFT_SHIFT_BITS) | (getWorkerId() << WORKER_ID_LEFT_SHIFT_BITS) | (0 << BATCH_FLAG_LEFT_SHIFT_BITS) | sequence; - } - - private boolean waitTolerateTimeDifferenceIfNeed(final long currentMilliseconds) { - if (lastMilliseconds <= currentMilliseconds) { - return false; - } - long timeDifferenceMilliseconds = lastMilliseconds - currentMilliseconds; - Preconditions.checkState(timeDifferenceMilliseconds < getMaxTolerateTimeDifferenceMilliseconds(), - "Clock is moving backwards, last time is %d milliseconds, current time is %d milliseconds", lastMilliseconds, currentMilliseconds); - try { - Thread.sleep(timeDifferenceMilliseconds); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return true; - } - - private long getWorkerId() { - long result = Long.valueOf(properties.getProperty("worker.id", String.valueOf(WORKER_ID))); - Preconditions.checkArgument(result >= 0L && result < WORKER_ID_MAX_VALUE); - return result; - } - - private int getMaxVibrationOffset() { - int result = Integer.parseInt(properties.getProperty("max.vibration.offset", String.valueOf(DEFAULT_VIBRATION_VALUE))); - Preconditions.checkArgument(result >= 0 && result <= SEQUENCE_MASK, "Illegal max vibration offset"); - return result; - } - - private int getMaxTolerateTimeDifferenceMilliseconds() { - return Integer.valueOf(properties.getProperty("max.tolerate.time.difference.milliseconds", String.valueOf(MAX_TOLERATE_TIME_DIFFERENCE_MILLISECONDS))); - } - - private long waitUntilNextTime(final long lastTime) { - long result = timeService.getCurrentMillis(); - while (result <= lastTime) { - result = timeService.getCurrentMillis(); - } - return result; - } - - private void vibrateSequenceOffset() { - sequenceOffset = sequenceOffset >= getMaxVibrationOffset() ? 0 : sequenceOffset + 1; - } - - @Override - public List generateKeyList(int genNum) { - long currentMilliseconds = timeService.getCurrentMillis(); - if (waitTolerateTimeDifferenceIfNeed(currentMilliseconds)) { - currentMilliseconds = timeService.getCurrentMillis(); - } - List data = new ArrayList(genNum); - for(int i=0; i> CACHED_TABLE_SUFFIX_BY_TENANT = null; - private Map> CACHED_TABLE_SUFFIX_BY_TABLE_NAME = null; - private Map GENERATOR_HOLDER = new HashMap(); - - @Resource - private ShardingInfoRepository shardingInfoRepository; - private ShardingSphereKeyGeneratorConfiguration config; - - public ShardingSphereService(ShardingSphereKeyGeneratorConfiguration config) { - this.config = config; - } - - public List generateKeyList(String tableName, int number){ - if(!GENERATOR_HOLDER.containsKey(tableName)) { - loadShardingKeyGenerator(tableName); - } - return GENERATOR_HOLDER.get(tableName).generateKeyList(number); - } - - public List getShardingInfoByTenantId(Long tenantId) { - if(CACHED_TABLE_SUFFIX_BY_TENANT == null) { - loadCacheTableShardingInfo(); - } - return CACHED_TABLE_SUFFIX_BY_TENANT.get(tenantId); - } - - private synchronized void loadCacheTableShardingInfo() { - if(CACHED_TABLE_SUFFIX_BY_TENANT != null && CACHED_TABLE_SUFFIX_BY_TABLE_NAME != null) { - return; - } - List dataList = this.shardingInfoRepository.findListBySql("1=1"); - Map> tempData = new HashMap>(); - Map> tempDataTableName = new HashMap>(); - for(ShardingInfoEntity item: dataList) { - List tempItem = tempData.getOrDefault(item.getTenantId(), new ArrayList()); - tempItem.add(item); - tempData.put(item.getTenantId(), tempItem); - - List tempItemTableName = tempDataTableName.getOrDefault(item.getTableName(), new ArrayList()); - tempItemTableName.add(item); - tempDataTableName.put(item.getTableName(), tempItemTableName); - } - CACHED_TABLE_SUFFIX_BY_TENANT = tempData; - CACHED_TABLE_SUFFIX_BY_TABLE_NAME = tempDataTableName; - } - - private synchronized void loadShardingKeyGenerator(String tableName) { - if(GENERATOR_HOLDER.containsKey(tableName)) { - return; - } - ShardingKeyGeneratorExt generator = new ShardingKeyGeneratorImpl(); - generator.loalConfig(config); - GENERATOR_HOLDER.put(tableName, generator); - } - - public List getShardingInfoByTableNames(String[] broadcastTableNames) { - if(broadcastTableNames == null || broadcastTableNames.length == 0) { - return null; - } - if(CACHED_TABLE_SUFFIX_BY_TABLE_NAME == null) { - loadCacheTableShardingInfo(); - } - List dataList = new ArrayList(); - for(String item: broadcastTableNames) { - List tempData = CACHED_TABLE_SUFFIX_BY_TABLE_NAME.get(item); - if(tempData != null && !tempData.isEmpty()) { - dataList.addAll(tempData); - } - } - return dataList; - } -} diff --git a/src/main/java/com/taover/repository/shardingsphere/ShardingTableAlgorithmHint.java b/src/main/java/com/taover/repository/shardingsphere/ShardingTableAlgorithmHint.java deleted file mode 100644 index df4e0a5..0000000 --- a/src/main/java/com/taover/repository/shardingsphere/ShardingTableAlgorithmHint.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.taover.repository.shardingsphere; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm; -import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue; - -public class ShardingTableAlgorithmHint implements HintShardingAlgorithm { - Log log = LogFactory.getLog(ShardingTableAlgorithmHint.class); - - Properties prop = null; - - public ShardingTableAlgorithmHint() { } - - @Override - public Collection doSharding(Collection availableTargetNames, HintShardingValue shardingValue) { - Collection values = shardingValue.getValues(); - if(values == null || values.isEmpty()) { - String message = shardingValue.getLogicTableName()+"已启用分库分表,SQL语句请指定tenant_id 或 使用封装好的DAO层方法"; - log.error(message); - throw new RuntimeException(message); - } - Set result = new HashSet(availableTargetNames); - for(String item: values) { - result.add(shardingValue.getLogicTableName()+item); - } - return result; - } - - @Override - public String getType() { - return "TABLE-HINT"; - } - - @Override - public Properties getProps() { - return this.prop; - } - - @Override - public void setProps(Properties props) { - this.prop = props; - } - - @Override - public void init() { - System.out.println("ShardingTableAlgorithmHint:init"); - } -} diff --git a/src/main/java/com/taover/repository/spring/autoconfigure/TaoverRepositoryAutoConfiguration.java b/src/main/java/com/taover/repository/spring/autoconfigure/TaoverRepositoryAutoConfiguration.java new file mode 100644 index 0000000..53a134e --- /dev/null +++ b/src/main/java/com/taover/repository/spring/autoconfigure/TaoverRepositoryAutoConfiguration.java @@ -0,0 +1,24 @@ +package com.taover.repository.spring.autoconfigure; + +import javax.annotation.Resource; + +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; + +import com.taover.repository.jdbctemplate.JdbcTemplateWrapperTenant; +import com.taover.repository.jdbctemplate.JdbcTemplateWrapperTenantImpl; + +@Configuration +@AutoConfigureAfter(JdbcTemplateAutoConfiguration.class) +public class TaoverRepositoryAutoConfiguration { + @Resource + private JdbcTemplate jdbcTemplate; + + @Bean + public JdbcTemplateWrapperTenant jdbcTemplateWrapperTenant() { + return new JdbcTemplateWrapperTenantImpl(this.jdbcTemplate); + } +} diff --git a/src/main/resources/META-INF/services/org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator b/src/main/resources/META-INF/services/org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator deleted file mode 100644 index fc776ea..0000000 --- a/src/main/resources/META-INF/services/org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator +++ /dev/null @@ -1 +0,0 @@ -com.taover.repository.shardingsphere.ShardingKeyGeneratorImpl \ No newline at end of file diff --git a/src/main/resources/META-INF/spring.factories b/src/main/resources/META-INF/spring.factories index 8df3599..9470ce1 100644 --- a/src/main/resources/META-INF/spring.factories +++ b/src/main/resources/META-INF/spring.factories @@ -1 +1 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.taover.repository.autoconfigure.TaoverRepositoryAutoConfiguration \ No newline at end of file +org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.taover.repository.spring.autoconfigure.TaoverRepositoryAutoConfiguration \ No newline at end of file diff --git a/src/test/java/com/taover/repository/test/TestAutoconfigure.java b/src/test/java/com/taover/repository/test/TestAutoconfigure.java index 312cb79..9ad0a96 100644 --- a/src/test/java/com/taover/repository/test/TestAutoconfigure.java +++ b/src/test/java/com/taover/repository/test/TestAutoconfigure.java @@ -18,20 +18,16 @@ import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.scheduling.annotation.EnableScheduling; -import com.taover.repository.jdbctemplate.JdbcTemplateBroadcast; import com.taover.repository.jdbctemplate.JdbcTemplateWrapperTenant; @SpringBootApplication @EnableScheduling public class TestAutoconfigure { - private static JdbcTemplateBroadcast jdbcTemplateBroadcast; private static JdbcTemplateWrapperTenant jdbcTemplateWrapperTenant; private static JdbcTemplate jdbcTemplate; - - + public static void main(String args[]) { ConfigurableApplicationContext context = SpringApplication.run(TestAutoconfigure.class, args); - jdbcTemplateBroadcast = context.getBean(JdbcTemplateBroadcast.class); jdbcTemplateWrapperTenant = context.getBean(JdbcTemplateWrapperTenant.class); jdbcTemplate = context.getBean(JdbcTemplate.class); @@ -67,7 +63,7 @@ public class TestAutoconfigure { private static void testSimpleQuery() { String sql = "select id from demo limit 1; "; - System.out.println(jdbcTemplate.queryForObject(sql, BigDecimal.class)); + System.out.println(jdbcTemplateWrapperTenant.queryForObject(sql, BigDecimal.class, null)); } private static void testExpressSql() { @@ -502,7 +498,6 @@ public class TestAutoconfigure { } public static void testBroadCast() { - System.out.println(jdbcTemplateBroadcast.queryForObject("select id from wxorder_order order by id desc limit 5 ", String.class, new String[]{"wxorder_order"})); System.out.println(jdbcTemplateWrapperTenant.queryForObject("select id from wxorder_order limit 1", Long.class, 1L)); System.out.println(jdbcTemplateWrapperTenant.queryForList("select * from wxorder_order limit 1", 1L)); System.out.println(jdbcTemplateWrapperTenant.queryForList("select * from wxorder_order limit 1", 2L)); diff --git a/src/test/java/com/taover/repository/test/TestMapper.java b/src/test/java/com/taover/repository/test/TestMapper.java index 58903cf..15aafdc 100644 --- a/src/test/java/com/taover/repository/test/TestMapper.java +++ b/src/test/java/com/taover/repository/test/TestMapper.java @@ -7,6 +7,8 @@ import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import com.alibaba.druid.pool.DruidDataSourceFactory; +import com.taover.repository.jdbctemplate.JdbcTemplateWrapperTenant; +import com.taover.repository.jdbctemplate.JdbcTemplateWrapperTenantImpl; import com.taover.repository.test.repository.CommonRegionRepository; public class TestMapper { @@ -20,10 +22,10 @@ public class TestMapper { DataSource ds = null; try { ds = new DruidDataSourceFactory().createDataSource(properties); - JdbcTemplate template = new JdbcTemplate(ds); + JdbcTemplateWrapperTenant template = new JdbcTemplateWrapperTenantImpl(new JdbcTemplate(ds)); //System.out.println(template.queryForObject("select count(*) from wxorder_order", Integer.class)); CommonRegionRepository repo = new CommonRegionRepository(template); - System.out.println(repo.findListBySql("1=1")); + System.out.println(repo.findListBySql("1=1", null)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); diff --git a/src/test/java/com/taover/repository/test/repository/CommonRegionRepository.java b/src/test/java/com/taover/repository/test/repository/CommonRegionRepository.java index 23a44a4..231ca60 100644 --- a/src/test/java/com/taover/repository/test/repository/CommonRegionRepository.java +++ b/src/test/java/com/taover/repository/test/repository/CommonRegionRepository.java @@ -1,16 +1,15 @@ package com.taover.repository.test.repository; -import org.springframework.jdbc.core.JdbcTemplate; +import com.taover.repository.CustomJdbcTemplateWrapperTenant; +import com.taover.repository.jdbctemplate.JdbcTemplateWrapperTenant; -import com.taover.repository.CustomJdbcTemplate; - -public class CommonRegionRepository extends CustomJdbcTemplate{ +public class CommonRegionRepository extends CustomJdbcTemplateWrapperTenant{ public static int TYPE_PROVINCE = 1; public static int TYPE_CITY = 2; public static int TYPE_DISTRICT = 3; public static Long PROVINCE_PARENT_ID = 1L; - public CommonRegionRepository(JdbcTemplate jdbcTemplate) throws Exception { + public CommonRegionRepository(JdbcTemplateWrapperTenant jdbcTemplate) throws Exception { super(jdbcTemplate); } } diff --git a/src/test/resources/META-INF/services/org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator b/src/test/resources/META-INF/services/org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator deleted file mode 100644 index fc776ea..0000000 --- a/src/test/resources/META-INF/services/org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator +++ /dev/null @@ -1 +0,0 @@ -com.taover.repository.shardingsphere.ShardingKeyGeneratorImpl \ No newline at end of file diff --git a/src/test/resources/META-INF/spring.factories b/src/test/resources/META-INF/spring.factories index a16dcbc..9470ce1 100644 --- a/src/test/resources/META-INF/spring.factories +++ b/src/test/resources/META-INF/spring.factories @@ -1 +1 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.taover.repository.autoconfigure.RepositoryAutoConfiguration \ No newline at end of file +org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.taover.repository.spring.autoconfigure.TaoverRepositoryAutoConfiguration \ No newline at end of file diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index fcc419d..0640126 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -1,54 +1,11 @@ -server.port=80 -server.session.timeout=3600 - -spring.servlet.multipart.max-file-size=10MB -spring.servlet.multipart.max-request-size=20MB - -spring.jackson.time-zone=GMT+8 -spring.jackson.date-format=yyyy-MM-dd HH:mm:ss -spring.mvc.dateFormat = yyyy-MM-dd HH:mm:ss -spring.gson.serialize-nulls=true - -spring.mvc.dispatch-options-request=true - -# shardingspere -spring.shardingsphere.datasource.names=ds0 -spring.shardingsphere.datasource.common.type=com.alibaba.druid.pool.DruidDataSource -spring.shardingsphere.datasource.common.driver-class-name=com.mysql.cj.jdbc.Driver -spring.shardingsphere.datasource.ds0.url=jdbc:mysql://rdsifmezqifmezqo.mysql.rds.aliyuncs.com:3306/bzyun_wxorder?characterEncoding=UTF-8 -spring.shardingsphere.datasource.ds0.username=tylife -spring.shardingsphere.datasource.ds0.password=lexi365 -spring.shardingsphere.datasource.ds0.initial-size=10 -spring.shardingsphere.datasource.ds0.max-active=20 -spring.shardingsphere.datasource.ds0.min-idle=5 -spring.shardingsphere.datasource.ds0.max-wait=60000 - -spring.shardingsphere.datasource.ds1.url=jdbc:mysql://121.42.142.102:3306/bzyun_wxorder?characterEncoding=UTF-8 -spring.shardingsphere.datasource.ds1.username=dev -spring.shardingsphere.datasource.ds1.password=taover02 -spring.shardingsphere.datasource.ds1.initial-size=10 -spring.shardingsphere.datasource.ds1.max-active=20 -spring.shardingsphere.datasource.ds1.min-idle=5 -spring.shardingsphere.datasource.ds1.max-wait=60000 - -#spring.shardingsphere.rules.sharding.tables.wxorder_order.actual-data-nodes=ds0.wxorder_order -#spring.shardingsphere.rules.sharding.tables.wxorder_order.database-strategy.hint.database_hint.sharding-algorithm-name=database_hint -#spring.shardingsphere.rules.sharding.tables.wxorder_order.table-strategy.hint.table_hint.sharding-algorithm-name=table_hint -#spring.shardingsphere.rules.sharding.tables.wxorder_order.key-generate-strategy.column=id -#spring.shardingsphere.rules.sharding.tables.wxorder_order.key-generate-strategy.key-generator-name=SNOWFLAKE-SELF - -#spring.shardingsphere.rules.sharding.sharding-algorithms.database_hint.type=HINT -#spring.shardingsphere.rules.sharding.sharding-algorithms.database_hint.algorithm-class-name=com.taover.repository.shardingsphere.ShardingDatabaseAlgorithmHint -#spring.shardingsphere.rules.sharding.sharding-algorithms.table_hint.type=HINT -#spring.shardingsphere.rules.sharding.sharding-algorithms.table_hint.algorithm-class-name=com.taover.repository.shardingsphere.ShardingTableAlgorithmHint - -taover.sharding.workerId=1 -taover.sharding.maxVibrationOffset=3 -taover.sharding.maxTolerateTimeDifferenceMilliseconds=1000 - -#spring.shardingsphere.sharding.default-key-generator.key-generator.column=id -#spring.shardingsphere.sharding.default-key-generator.type=SNOWFLAKE-SELF -#spring.shardingsphere.sharding.default-key-generator.props.worker.id=1 -#spring.shardingsphere.sharding.default-key-generator.props.max.vibration.offset=3 -#spring.shardingsphere.sharding.default-key-generator.props.max.tolerate.time.difference.milliseconds=1000 +#DB info +spring.datasource.url=jdbc:mysql://rdsifmezqifmezqo.mysql.rds.aliyuncs.com:3306/bzyun_wxorder?characterEncoding=UTF8&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT%2B8 +spring.datasource.username=tylife +spring.datasource.password=lexi365 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +spring.datasource.druid.initial-size=10 +spring.datasource.druid.max-active=20 +spring.datasource.druid.min-idle=5 +spring.datasource.druid.max-wait=60000 -- libgit2 0.21.2