├── APITemplate.java ├── AutoValueFromSqlUtil.java ├── BaseMapper.java ├── BaseMapperAspect.java ├── CRUDTask.java ├── GenerateFromDB.java ├── JDBCUtil.java ├── JDBCUtilHikari.java ├── README.md ├── RequestValue.java ├── SQLBuilderUtil.java ├── test └── test.config /APITemplate.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import com.example.demo.commom.RespValue; 4 | import com.example.demo.mapper.BaseMapper; 5 | import com.example.demo.util.*; 6 | import io.swagger.annotations.ApiImplicitParam; 7 | import io.swagger.annotations.ApiImplicitParams; 8 | import lombok.extern.slf4j.Slf4j; 9 | import net.sf.jsqlparser.JSQLParserException; 10 | import net.sf.jsqlparser.parser.ParseException; 11 | import org.springframework.web.bind.annotation.*; 12 | import javax.annotation.Resource; 13 | import javax.servlet.http.HttpServletRequest; 14 | import java.util.*; 15 | import java.util.regex.Matcher; 16 | 17 | import static com.example.demo.util.AutoValueFromSqlUtil.*; 18 | import static com.example.demo.util.SQLBuilderUtil.*; 19 | 20 | 21 | @Slf4j 22 | @RestController 23 | @RequestMapping(value="/user/",method = {RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT}) 24 | public class APITemplate { 25 | 26 | @Resource 27 | private BaseMapper baseMapper; 28 | 29 | @PostMapping(value = "insert") 30 | public RespValue insert(String name,Integer number,String password){ 31 | String currentDateString = TimeUtil.getCurrentDateString(); 32 | String sql = "INSERT INTO user(name,password,number,time) VALUES(?,?,?,?)"; 33 | Map map = new HashMap(); 34 | int result = baseMapper.insertForID(sql,map,name,password,number,currentDateString); 35 | System.out.println("id = " + map.get("id")); 36 | return new RespValue(0,"插入成功",map.get("id")); 37 | } 38 | 39 | @PostMapping(value = "insert1") 40 | public RespValue insert1(String name,Integer number,String password){ 41 | String sql = insertSQL("user","name,password,number,time"); 42 | Map map = new HashMap(); 43 | int result = baseMapper.insertForID(sql,map,name,password,number,TimeUtil.getCurrentDateString()); 44 | return new RespValue(0,"插入成功",map.get("id")); 45 | } 46 | 47 | 48 | @PostMapping(value = "insert2") 49 | public RespValue insert2(HttpServletRequest request) throws JSQLParserException { 50 | //String sql = insertSQL("user","name,password,number,time"); 51 | String sql = insertSQL("user");//解析表结构进行自动生成SQL 52 | //List args = insertValue(sql,request);//解析SQL语句进行自动填充,缺点是效率略低,不能准确识别类型 53 | //List args = fillValueByNameString(request,"name,password,Integer number");//指定参数和类型进行填充,缺点是需要指定参数 54 | List args = fillValueByTableForInsert(request,"user");//解析表结构进行自动填充,缺点是需要预加载表结构 55 | 56 | args.set(3,TimeUtil.getCurrentDateString()); 57 | int result = baseMapper.insert(sql,args.toArray()); 58 | return new RespValue(0,"插入成功",result); 59 | } 60 | 61 | @PostMapping("/statistics") 62 | public RespValue statistics() { 63 | long start = System.currentTimeMillis(); //获取开始时间 64 | LinkedHashMap result = new LinkedHashMap(); 65 | //总数 66 | result.put("total_num", baseMapper.count("SELECT COUNT(*) as num FROM user")); 67 | //每个分数的计数,按分数倒排 68 | result.put("number_num", baseMapper.select("SELECT number,COUNT(*) as num FROM user GROUP BY number ORDER BY number DESC")); 69 | //每个用户的最高分,按分数倒排 70 | result.put("user_max_number", baseMapper.select("SELECT name,MAX(number) as max_number FROM user GROUP BY name ORDER BY max_number DESC")); 71 | long end = System.currentTimeMillis(); //获取结束时间 72 | System.out.println("111程序运行时间: " + (end - start) + "ms"); 73 | return new RespValue(0, result); 74 | } 75 | 76 | @PostMapping(value="delete") 77 | public RespValue delete(Integer id){ 78 | int result = baseMapper.delete("delete from user where id=?",id); 79 | return new RespValue(0,"删除成功",result); 80 | } 81 | 82 | @PostMapping(value="delete1") 83 | public RespValue delete1(Integer id){ 84 | int result = baseMapper.delete(deleteSQL("user"),id); 85 | return new RespValue(0,"删除成功",result); 86 | } 87 | 88 | @PostMapping(value="delete2") 89 | public RespValue delete2(HttpServletRequest request) { 90 | int result = baseMapper.delete(deleteSQL("user"),idValue(request)); 91 | //int result = baseMapper.delete(deleteSQL("user"),fillValueByName(request,"Integer id").toArray()); 92 | return new RespValue(0,"删除成功",result); 93 | } 94 | 95 | @PostMapping(value="deletes") 96 | public RespValue deletes(String ids){ 97 | 98 | int result = baseMapper.delete("delete from user where id in ("+ids+")"); 99 | return new RespValue(0,"删除成功",result); 100 | } 101 | 102 | @PostMapping(value = "update") 103 | public RespValue update(Integer id,String name,Integer number,String password){ 104 | String sqlStr = "update user set name=?,password=?,number=? where id=?"; 105 | int result = baseMapper.update(sqlStr,name,password,number,id); 106 | return new RespValue(0,"修改成功",result); 107 | } 108 | 109 | @PostMapping(value = "update1") 110 | public RespValue update1(Integer id,String name,Integer number,String password){ 111 | String sqlStr = updateSQL("user","name,password,number"); 112 | int result = baseMapper.update(sqlStr,name,password,number,id); 113 | return new RespValue(0,"修改成功",result); 114 | } 115 | 116 | @PostMapping(value = "update2") 117 | public RespValue update2(HttpServletRequest request) throws JSQLParserException { 118 | String sqlStr = updateSQL("user");//解析表结构进行自动生成SQL 119 | //List args = updateValueById(sqlStr,request);//解析SQL语句进行自动填充,缺点是效率略低,不能准确识别类型 120 | //List args = fillValueByNameString(request,"name,password,Integer number,Long id");//指定参数和类型进行填充,缺点是需要指定参数 121 | List args = fillValueByTableForUpdate(request,"user");//解析表结构进行自动填充,缺点是需要预加载表结构 122 | int result = baseMapper.update(sqlStr,args.toArray()); 123 | return new RespValue(0,"修改成功",result); 124 | } 125 | 126 | @PostMapping(value = "findObjectById") 127 | public RespValue findObjectById(Integer id){ 128 | LinkedHashMap result = baseMapper.get("SELECT * FROM user where id=?",id); 129 | return new RespValue(0,"",result); 130 | } 131 | 132 | @PostMapping(value = "findObjectById1") 133 | public RespValue findObjectById1(Integer id){ 134 | LinkedHashMap result = baseMapper.get(getSQL("user"),id); 135 | return new RespValue(0,"",result); 136 | } 137 | 138 | @PostMapping(value = "findObjectById2") 139 | public RespValue findObjectById2(HttpServletRequest request) { 140 | LinkedHashMap result = baseMapper.get(getSQL("user"),idValue(request)); 141 | return new RespValue(0,"",result); 142 | } 143 | 144 | @PostMapping(value="findListByCondition") 145 | public RespValue findListByCondition(String name,Integer number,String password, 146 | String orderColumn,String orderDirection,Integer pageNum,Integer pageSize){ 147 | 148 | //String sqlStr = "SELECT * FROM user where 1=1 and name like CONCAT('%',IFNULL(?,''),'%') and password=? and number=? "; 149 | String sqlStr = "SELECT * FROM user where 1=1 and name like ? and password like ? and number=? "; 150 | sqlStr = SQLBuilderUtil.pageAndOrderBuilder(sqlStr,orderColumn,orderDirection,pageNum,pageSize); 151 | List> result = baseMapper.select(sqlStr,"%"+name+"%","%"+password+"%",number); //"%"+name+"%" 152 | //System.out.println("result = " + JSON.toJSONString(result,true)); 153 | return new RespValue(0,"",result); 154 | } 155 | 156 | @PostMapping(value="findListByCondition1") 157 | public RespValue findListByCondition1(String name,Integer number,String password, 158 | String orderColumn,String orderDirection,Integer pageNum,Integer pageSize){ 159 | //String sqlStr = showSQL("user","(name = '王五' or name = ?) and name like ? and password like ? and number =? and name in ('王五','王五') and abs(id)>0 and id between 1 and 100000 and id is not null"); 160 | String sqlStr = showSQL("user","name like ? and password like ? and number=?"); 161 | sqlStr = pageAndOrderBuilder(sqlStr,orderColumn,orderDirection,pageNum,pageSize); 162 | List> result = baseMapper.select(sqlStr,"%"+name+"%","%"+password+"%",number); //"%"+name+"%" 163 | //System.out.println("result = " + JSON.toJSONString(result,true)); 164 | return new RespValue(0,"",result); 165 | } 166 | 167 | 168 | @GetMapping("/countByCondition") 169 | public RespValue countByCondition(String name,Integer number,String password){ 170 | String sqlStr = "SELECT count(*) FROM user where 1=1 and name like ? and password like ? and number=? "; 171 | long result = baseMapper.count(sqlStr,"%"+name+"%","%"+password+"%",number); 172 | return new RespValue(0,"",result); 173 | } 174 | 175 | @GetMapping("/countByCondition1") 176 | public RespValue countByCondition1(String name,Integer number,String password){ 177 | String sqlStr = countSQL("user","name like ? and password like ? and number=?"); 178 | long result = baseMapper.count(sqlStr,"%"+name+"%","%"+password+"%",number); 179 | return new RespValue(0,"",result); 180 | } 181 | 182 | 183 | } 184 | 185 | -------------------------------------------------------------------------------- /AutoValueFromSqlUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.util; 2 | 3 | import com.example.demo.client.TestParseSQL; 4 | import com.example.demo.commom.RequestValue; 5 | import net.sf.jsqlparser.JSQLParserException; 6 | import net.sf.jsqlparser.expression.Expression; 7 | import net.sf.jsqlparser.expression.operators.conditional.AndExpression; 8 | import net.sf.jsqlparser.parser.*; 9 | import net.sf.jsqlparser.schema.Column; 10 | import net.sf.jsqlparser.schema.Table; 11 | import net.sf.jsqlparser.statement.Statement; 12 | import net.sf.jsqlparser.statement.insert.Insert; 13 | import net.sf.jsqlparser.statement.select.PlainSelect; 14 | import net.sf.jsqlparser.statement.select.Select; 15 | import net.sf.jsqlparser.statement.select.SelectBody; 16 | import net.sf.jsqlparser.statement.update.Update; 17 | import net.sf.jsqlparser.statement.update.UpdateSet; 18 | import org.apache.commons.lang3.StringUtils; 19 | 20 | import javax.servlet.http.HttpServletRequest; 21 | import java.lang.reflect.InvocationTargetException; 22 | import java.lang.reflect.Method; 23 | import java.util.ArrayList; 24 | import java.util.Arrays; 25 | import java.util.List; 26 | import java.util.regex.Matcher; 27 | import java.util.regex.Pattern; 28 | 29 | import static com.example.demo.util.SQLBuilderUtil.typeColumns; 30 | 31 | public class AutoValueFromSqlUtil { 32 | 33 | private static Pattern pattern = Pattern.compile("^\\w[-\\w.+]*$"); 34 | public static boolean isColumn(String input){ 35 | 36 | //String regex = "^\\w[-\\w.+]*$"; // 替换成你的正则表达式 37 | //String input = "abs(id)"; // 替换成你的待匹配字符串 38 | //String input = "name"; // 替换成你的待匹配字符串 39 | //Pattern pattern = Pattern.compile(regex); 40 | Matcher matcher = pattern.matcher(input); 41 | boolean isMatched = matcher.matches(); 42 | return isMatched; 43 | } 44 | 45 | 46 | 47 | public static List insertValue(String sql, HttpServletRequest request) throws JSQLParserException { 48 | RequestValue r = new RequestValue(request); 49 | Insert insert = (Insert) CCJSqlParserUtil.parse(sql); 50 | System.out.println("插入的表" + insert.getTable()); 51 | System.out.println("插入的列" + insert.getColumns()); 52 | System.out.println("插入的值" + insert.getItemsList()); 53 | 54 | List columns = insert.getColumns(); 55 | List args = new ArrayList(); 56 | // for (int i = 0; i < columns.size(); i++) { 57 | // args.add(r.s(columns.get(i).getColumnName())); 58 | // } 59 | columns.forEach(column -> args.add(r.getObject(column.getColumnName()))); 60 | return args; 61 | } 62 | 63 | // public static List insertValue(String sql, Object obj) throws JSQLParserException, InvocationTargetException, IllegalAccessException { 64 | // Insert insert = (Insert) CCJSqlParserUtil.parse(sql); 65 | // System.out.println("插入的表" + insert.getTable()); 66 | // System.out.println("插入的列" + insert.getColumns()); 67 | // System.out.println("插入的值" + insert.getItemsList()); 68 | // 69 | // List columns = insert.getColumns(); 70 | // List args = new ArrayList(); 71 | //// for (int i = 0; i < columns.size(); i++) { 72 | //// args.add(r.s(columns.get(i).getColumnName())); 73 | //// } 74 | // //columns.forEach(column -> args.add(r.getObject(column.getColumnName()))); 75 | // 76 | // 77 | // for (int i = 0; i < columns.size(); i++) { 78 | // Method m = obj.class.getMethod("get"+ StringUtils.capitalize(columns.get(i).getColumnName())); 79 | // args.add(m.invoke(obj,null)); 80 | // 81 | // } 82 | // 83 | // 84 | // return args; 85 | // } 86 | 87 | public static List updateValue(String sql, HttpServletRequest request) throws JSQLParserException { 88 | RequestValue r = new RequestValue(request); 89 | List args = new ArrayList(); 90 | Update update = (Update) CCJSqlParserUtil.parse(sql); 91 | System.out.println("更惨的表" + update.getTable()); 92 | for (UpdateSet updateSet : update.getUpdateSets()) { 93 | updateSet.getColumns().forEach(System.out::println); 94 | updateSet.getColumns().forEach(column -> args.add(r.getObject(column.getColumnName()))); 95 | } 96 | return args; 97 | } 98 | 99 | public static List updateValueById(String sql, HttpServletRequest request) throws JSQLParserException { 100 | RequestValue r = new RequestValue(request); 101 | List args = new ArrayList(); 102 | Update update = (Update) CCJSqlParserUtil.parse(sql); 103 | System.out.println("更惨的表" + update.getTable()); 104 | for (UpdateSet updateSet : update.getUpdateSets()) { 105 | updateSet.getColumns().forEach(System.out::println); 106 | updateSet.getColumns().forEach(column -> args.add(r.getObject(column.getColumnName()))); 107 | } 108 | args.add(r.getLong("id")); 109 | return args; 110 | } 111 | 112 | public static long idValue(HttpServletRequest request) { 113 | RequestValue r = new RequestValue(request); 114 | return r.getLong("id"); 115 | } 116 | 117 | public static List selectValue(String sql, HttpServletRequest request) throws ParseException { 118 | RequestValue r = new RequestValue(request); 119 | List columnList = new ArrayList(); 120 | List args = new ArrayList(); 121 | args.add(r); 122 | args.add(columnList); 123 | /** 创建SQL语句解析器实例 */ 124 | CCJSqlParser parser = CCJSqlParserUtil.newParser(sql); 125 | /** 解析SQL语句 */ 126 | Statement stmt = parser.Statement(); 127 | 128 | /** 使用 LogVisiter对象遍历AST的所有节点 */ 129 | parser.getASTRoot().jjtAccept(new LogVisitor(), args); 130 | System.out.printf("sql--> %s\n",stmt); 131 | args.remove(0); 132 | args.remove(0); 133 | System.out.printf("Handle columns--> %s\n",columnList.toString()); 134 | System.out.printf("Fill args--> %s\n",args.toString()); 135 | return args; 136 | } 137 | 138 | public static List fillValueByName(HttpServletRequest request,String ...names) { 139 | RequestValue r = new RequestValue(request); 140 | List args = new ArrayList(); 141 | //List argsType = new ArrayList(); 142 | 143 | for(int i=0;i %s\n", Arrays.toString(names)); 172 | System.out.printf("Fill args--> %s\n",args.toString()); 173 | //System.out.printf("Args type--> %s\n",argsType.toString()); 174 | return args; 175 | } 176 | 177 | 178 | public static List fillValueByNameString(HttpServletRequest request,String namesString) { 179 | 180 | String[] names = namesString.split("\\,"); 181 | List args = fillValueByName(request,names); 182 | return args; 183 | } 184 | 185 | public static List fillValueByTableForInsert(HttpServletRequest request,String table) { 186 | String namesString = typeColumns(table); 187 | List args = fillValueByNameString(request,namesString); 188 | return args; 189 | } 190 | 191 | public static List fillValueByTableForUpdate(HttpServletRequest request,String table) { 192 | String namesString = typeColumns(table); 193 | namesString = namesString + ",Long id"; 194 | List args = fillValueByNameString(request,namesString); 195 | return args; 196 | } 197 | 198 | 199 | /** 200 | * 遍历所有节点的{@link CCJSqlParserVisitor} 接口实现类 201 | * @author 202 | * 203 | */ 204 | static class LogVisitor extends CCJSqlParserDefaultVisitor { 205 | 206 | @Override 207 | public Object visit(SimpleNode node, Object data) { 208 | 209 | List args = (ArrayList) data; 210 | RequestValue r = (RequestValue) args.get(0); 211 | //args.remove(0); 212 | List columnList = (List) args.get(1); 213 | 214 | String value0=null; 215 | String value1=null; 216 | String value2=null; 217 | 218 | String[] strs=null; 219 | 220 | Object value = node.jjtGetValue(); 221 | /** 根据节点类型找出表名和字段名节点,对名字加上双引号 */ 222 | //1. COLUMN 223 | if (node.getId() == CCJSqlParserTreeConstants.JJTCOLUMN) { 224 | //System.out.printf("1. column: %s \n",value.toString()); 225 | Column column = (Column)value; 226 | // column.setColumnName("\"" + column.getColumnName() + "\""); 227 | Table table = column.getTable(); 228 | if(null != table){ 229 | // table.setName("\"" + table.getName() + "\""); 230 | } 231 | } 232 | //2. TABLE 233 | else if (node.getId() == CCJSqlParserTreeConstants.JJTTABLE) { 234 | //System.out.printf("2. table: %s \n",value.toString()); 235 | Table table = (Table)value; 236 | if(null != table){ 237 | // table.setName("\"" + table.getName() + "\""); 238 | } 239 | } 240 | //3. REGULAR CONDITION-14 241 | else if(node.getId() == CCJSqlParserTreeConstants.JJTREGULARCONDITION) { 242 | 243 | System.out.printf("3. CONDITION: %s \n",value.toString()); 244 | strs= value.toString().split(" "); 245 | if (strs.length>=3) { 246 | value0 = strs[0].trim(); 247 | value1 = strs[1].trim(); 248 | value2 = strs[2].trim(); 249 | 250 | if(isColumn(value0) && value2.equals("?")) 251 | { 252 | //args.add(value0.toString()); 253 | columnList.add(value0); 254 | System.out.println("Handle column = " + value0 + ", fill value = " + r.getObject(value0)); 255 | args.add(r.getObject(value0)); 256 | } 257 | System.out.printf("3.1. CONDITION-COLUMN:%s\n",value0 ); 258 | System.out.printf("3.2. CONDITION-OPERATOR:%s\n",value1 ); 259 | System.out.printf("3.3. CONDITION-VALUE:%s\n",value2 ); 260 | // if (node.getId() == CCJSqlParserTreeConstants.JJTCOLUMN) { 261 | // System.out.printf("4.1. column: %s \n", value2.toString()); 262 | // } 263 | 264 | } 265 | 266 | } 267 | //4. LIKE EXPRESSION -16 268 | else if(node.getId() == CCJSqlParserTreeConstants.JJTLIKEEXPRESSION) 269 | { 270 | System.out.printf("4. LIEK CONDITION: %s \n",value.toString()); 271 | strs= value.toString().split(" "); 272 | if (strs.length>=3) { 273 | value0 = strs[0].trim(); 274 | value1 = strs[1].trim(); 275 | value2 = strs[2].trim(); 276 | if(isColumn(value0) && value2.equals("?")) 277 | { 278 | //args.add(value0.toString()); 279 | columnList.add(value0); 280 | System.out.println("Handle column = " + value0 + ", fill value = " + "%"+r.getString(value0)+"%"); 281 | args.add("%"+r.getString(value0)+"%"); 282 | } 283 | System.out.printf("4.1.LIKE CONDITION-COLUMN:%s\n",value0 ); 284 | System.out.printf("4.2.LIKE CONDITION-OPERATOR:%s\n",value1 ); 285 | System.out.printf("4.3.LIKE CONDITION-VALUE:%s\n",value2 ); 286 | 287 | } 288 | 289 | } 290 | //5. IN EXPRESSION-15 291 | else if(node.getId() == CCJSqlParserTreeConstants.JJTINEXPRESSION) { 292 | System.out.printf("5. IN CONDITION: %s \n",value.toString() ); 293 | String express=value.toString(); 294 | // String[] strs= value.toString().split(" "); 295 | if (express.contains("not") || express.contains("NOT")) 296 | { 297 | //System.out.println("NOT IN"); 298 | strs= value.toString().replace("NOT IN","").split(" ",2); 299 | // for(String str:strs) { 300 | // System.out.printf("6.1. CONDITION1:%s\n", str); 301 | // } 302 | if(strs.length>=2) { 303 | value0 = strs[0].trim(); 304 | value1 = "NOT IN"; 305 | value2 = strs[1].trim(); 306 | System.out.printf("5.1.IN CONDITION-COLUMN:%s\n",value0 ); 307 | System.out.printf("5.2.IN CONDITION-OPERATOR:%s\n",value1 ); 308 | System.out.printf("5.3.IN CONDITION-VALUE:%s\n",value2 ); 309 | } 310 | } 311 | else 312 | { 313 | //System.out.println("IN"); 314 | strs= value.toString().replace("IN","").split(" ",2); 315 | // for(String str:strs) { 316 | // System.out.printf("6.2. CONDITION1:%s\n", str); 317 | // } 318 | if(strs.length>=2) { 319 | value0 = strs[0].trim(); 320 | value1 = "IN"; 321 | value2 = strs[1].trim(); 322 | System.out.printf("5.1.IN CONDITION-COLUMN:%s\n",value0 ); 323 | System.out.printf("5.2.IN CONDITION-OPERATOR:%s\n",value1 ); 324 | System.out.printf("5.3.IN CONDITION-VALUE:%s\n",value2 ); 325 | } 326 | } 327 | // if(value2.toString().equals("?")) 328 | // { 329 | // args.add(value0.toString()); 330 | // } 331 | 332 | } 333 | //6. Function - 23 334 | else if(node.getId() == CCJSqlParserTreeConstants.JJTFUNCTION) 335 | { 336 | System.out.printf("6. FUNCITON CONDITION: %s \n",value.toString()); 337 | strs= value.toString().split("\\("); 338 | if (strs.length>=2) { 339 | value0 = strs[0].trim(); 340 | value1 = "("+strs[1].trim(); 341 | System.out.printf("6.1.LIKE CONDITION-FUNCITON:%s\n",value0 ); 342 | System.out.printf("6.2.LIKE CONDITION-VALUE:%s\n",value1 ); 343 | } 344 | // if(value2.toString().equals("?")) 345 | // { 346 | // args.add(value0.toString()); 347 | // } 348 | } 349 | else if(null != value){ 350 | /** 其他类型节点输出节点类型值,Java类型和节点值 */ 351 | //System.out.printf("0. :%d :%s :%s \n",node.getId(),value.getClass().getSimpleName(),value.toString()); 352 | } 353 | return super.visit(node, data); 354 | } 355 | } 356 | 357 | ///复杂条件不填充值,支持函数后手工按位置填充,,,也可以直接都用手工传值 358 | // public static List selectValue(String sql, HttpServletRequest request) throws JSQLParserException { 359 | // RequestValue r = new RequestValue(request); 360 | // List args = new ArrayList(); 361 | // Select select = (Select)CCJSqlParserUtil.parse(sql); 362 | // //获取select对象 363 | // SelectBody selectBody = select.getSelectBody(); 364 | // System.out.println(selectBody.toString()); 365 | // PlainSelect plainSelect=(PlainSelect) selectBody; 366 | // //表名 367 | // Table table= (Table) plainSelect.getFromItem(); 368 | // //表名称 369 | // System.out.println(table.getName()); 370 | // AndExpression andExpression = (AndExpression) plainSelect.getWhere(); 371 | // System.out.println("andExpression = " + andExpression); 372 | // 373 | // //andExpression.accept(); 374 | // 375 | // String[] split = andExpression.toString().split(" AND "); 376 | // for (String s : split) { 377 | // System.out.println("s : " + s); 378 | //// System.out.println("s.trim().split(\"\\\\s*\").length = " + s.trim().split("\\s+").length); 379 | //// for (String s1 : s.trim().split("\\s+")) { 380 | //// System.out.println("s1 = " + s1); 381 | //// } 382 | // if(s.trim().split("\\s+").length>3) continue; 383 | // if (s.contains("?")){ 384 | // if (s.contains(" = ")){ 385 | // String column=s.trim().split(" = ")[0].trim(); 386 | // System.out.println("column = " + column); 387 | // if(column.equals("1")) continue; 388 | // args.add(r.getObject(column)); 389 | // } else if (s.contains(" LIKE ")) { 390 | // String column=s.trim().split(" LIKE ")[0].trim(); 391 | // System.out.println("column = " + column); 392 | // args.add("%"+r.s(column)+"%"); 393 | // }else{ 394 | // System.out.println("复杂表达式,跳过填充 = " + s); 395 | // continue; 396 | // } 397 | // }else{ 398 | // System.out.println("无占位符,跳过填充 = " + s); 399 | // continue; 400 | // } 401 | // 402 | // } 403 | // return args; 404 | // } 405 | 406 | public static void main(String[] args) { 407 | 408 | 409 | } 410 | 411 | 412 | } 413 | 414 | 415 | -------------------------------------------------------------------------------- /BaseMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.mapper; 2 | 3 | import org.apache.ibatis.annotations.*; 4 | import org.apache.ibatis.mapping.StatementType; 5 | import org.springframework.stereotype.Repository; 6 | import java.util.LinkedHashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | @Repository 11 | @Mapper 12 | public interface BaseMapper { 13 | 14 | @Select("${sql}") 15 | List> select(String sql,Object ...args); 16 | 17 | @Select("${sql}") 18 | long count(String sql,Object ...args); 19 | 20 | @Select("${sql}") 21 | LinkedHashMap get(String sql,Object ...args); 22 | 23 | @Insert("${sql}") 24 | int insert(String sql,Object ...args); 25 | 26 | @Options(useGeneratedKeys = true, keyProperty = "map.id") 27 | @Insert("${sql}") 28 | int insertForID(String sql,Map map,Object ...args); 29 | 30 | @Update("${sql}") 31 | int update(String sql,Object ...args); 32 | 33 | @Delete("${sql}") 34 | int delete(String sql,Object ...args); 35 | 36 | @Update("${sql}") 37 | int execute(String sql,Object ...args); 38 | 39 | @Update({ 40 | "" 45 | }) 46 | int executeBatch(List sql,Object ...args); 47 | 48 | @Options(statementType = StatementType.CALLABLE, useCache = false) 49 | @Select("CALL ${sql}") 50 | List> call(String sql,Map map,Object ...args); 51 | } 52 | 53 | -------------------------------------------------------------------------------- /BaseMapperAspect.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.trigger.aspect; 2 | 3 | import org.aspectj.lang.ProceedingJoinPoint; 4 | import org.aspectj.lang.annotation.Around; 5 | import org.aspectj.lang.annotation.Aspect; 6 | import org.aspectj.lang.annotation.Pointcut; 7 | import org.springframework.stereotype.Component; 8 | 9 | import java.sql.Timestamp; 10 | import java.text.SimpleDateFormat; 11 | import java.time.LocalDateTime; 12 | import java.time.ZoneOffset; 13 | import java.util.*; 14 | import java.util.regex.Matcher; 15 | import java.util.regex.Pattern; 16 | 17 | @Component 18 | @Aspect 19 | public class BaseMapperAspect { 20 | //切入点表达式,路径一定要写正确了 21 | @Pointcut("execution( * com.example.demo.mapper.BaseMapper.*(..))") 22 | public void access() { 23 | } 24 | 25 | //环绕增强,是在before前就会触发 26 | @Around("access()") 27 | public Object around(ProceedingJoinPoint pjp) throws Throwable { 28 | System.out.println("-aop BaseMapperAspect环绕阶段-" + new Date()); 29 | 30 | 31 | String METHOD = pjp.getSignature().getName(); 32 | System.out.println("METHOD = " + METHOD); 33 | 34 | Object[] args = pjp.getArgs(); 35 | Object o = args[0]; 36 | if (o.getClass().getName().equals("java.lang.String")){ 37 | // if(METHOD.equals("insertForID") || METHOD.equals("call")){ 38 | // //args = nullFinderBuilderInsertForID(args); 39 | // }else{ 40 | // args = nullFinderBuilder(args); 41 | // } 42 | String sql = (String) o; 43 | if (METHOD.equals("select") || METHOD.equals("count") || METHOD.equals("update") || METHOD.equals("insert") || METHOD.equals("insertForID")) { 44 | String _sql = sql.replace("count(*)","*"); 45 | // if (_sql.contains("(") || _sql.contains(")") || _sql.contains(" or ") || _sql.contains(" OR ") || 46 | // _sql.contains(" between ") || _sql.contains(" BETWEEN ") || 47 | // _sql.contains(" is ") || _sql.contains(" IS ") || 48 | // _sql.contains(" in ") || _sql.contains(" IN ")) { 49 | // System.out.println("sql = " + sql); 50 | // System.out.println("复杂SQL不进行空值过滤"); 51 | // } 52 | // 53 | if (1==2) { 54 | System.out.println("sql = " + sql); 55 | System.out.println("复杂SQL不进行空值过滤"); 56 | } else { 57 | //args = nullFinderBuilder(args); 58 | if (METHOD.equals("insertForID")) { 59 | args = nullFinderBuilderInsertForID(args); 60 | } else { 61 | args = nullFinderBuilder(args); 62 | } 63 | //o = args[0]; 64 | sql = (String) args[0]; 65 | System.out.println("sql = " + sql); 66 | sql = nullFilterBuilder(METHOD, sql); 67 | System.out.println("sql = " + sql); 68 | } 69 | } 70 | sql = paramReplace(sql); 71 | args[0]= sql; 72 | 73 | }else{ 74 | List sql = (List) o; 75 | sql = paramReplace(sql); 76 | args[0]= sql; 77 | 78 | } 79 | 80 | Object result = pjp.proceed(args); 81 | System.out.println("result = " + result); 82 | if(result == null){ 83 | if(METHOD.equals("get")) { 84 | return new LinkedHashMap(); 85 | }else if(METHOD.equals("count")){ 86 | return Long.valueOf(0); 87 | } 88 | } 89 | 90 | System.out.println("result.getClass().getName() = " + result.getClass().getName()); 91 | 92 | if (result.getClass().getName().equals("java.util.ArrayList")){ 93 | 94 | formatTimeOfListMap((List>) result); 95 | }else if(result.getClass().getName().equals("java.util.LinkedHashMap")) { 96 | formatTimeOfObjectMap((LinkedHashMap) result); 97 | 98 | }else{ 99 | 100 | } 101 | 102 | return result; 103 | 104 | } 105 | 106 | 107 | private int getKeyStringCount(String str, String key) {//方法 108 | int count = 0; 109 | int index = 0; 110 | while((index = str.indexOf(key,index))!=-1){ 111 | index = index + key.length(); 112 | count++; 113 | } 114 | return count; 115 | } 116 | 117 | 118 | private String paramReplace(String param) { 119 | 120 | int mun = getKeyStringCount(param,"?"); 121 | //System.out.println("mun = " + mun); 122 | 123 | for (int i = 0; i < mun; i++) { 124 | param = param.replaceFirst("\\?","#{args["+i+"]}"); 125 | //System.out.println("param = " + param); 126 | } 127 | 128 | 129 | return param; 130 | 131 | } 132 | 133 | 134 | private List paramReplace(List paramList) { 135 | 136 | int total = 0; 137 | 138 | for (int j = 0; j < paramList.size(); j++) { 139 | 140 | String param = paramList.get(j); 141 | int mun = getKeyStringCount(param,"?"); 142 | //System.out.println("mun = " + mun); 143 | 144 | for (int i = total; i < mun+total; i++) { 145 | param = param.replaceFirst("\\?","#{args["+i+"]}"); 146 | //System.out.println("param = " + param); 147 | } 148 | total = total+mun; 149 | paramList.set(j,param); 150 | } 151 | 152 | return paramList; 153 | 154 | } 155 | 156 | private String nullFilterBuilder(String METHOD,String sqlStr) { 157 | if(METHOD.equals("select") || METHOD.equals("count")) { 158 | //清洗查询SQL中的空条件 159 | 160 | //sqlStr = sqlStr.replaceAll("\\s+\\)", ")"); 161 | sqlStr = sqlStr + " "; 162 | 163 | sqlStr = sqlStr.replaceAll("\\s*and\\s+\\w[-\\w.+]*\\s*(=|>|<|>=|<=|<>|!=)\\s*null\\s+(?!\\))", " "); 164 | sqlStr = sqlStr.replaceAll("\\s*and\\s+\\w[-\\w.+]*\\s*(=|>|<|>=|<=|<>|!=)\\s*'null'\\s+(?!\\))", " "); 165 | sqlStr = sqlStr.replaceAll("\\s*and\\s+\\w[-\\w.+]*\\s*like\\s*'%null%'\\s+(?!\\))", " "); 166 | sqlStr = sqlStr.replaceAll("\\s+", " "); 167 | sqlStr = sqlStr.trim(); 168 | } 169 | if(METHOD.equals("update")) { 170 | //清洗更新SQL中的空值 171 | sqlStr = sqlStr.replaceAll("\\w[-\\w.+]*\\s*=\\s*null\\s*,?", ""); 172 | sqlStr = sqlStr.replaceAll("\\w[-\\w.+]*\\s*=\\s*'null'\\s*,?", ""); 173 | sqlStr = sqlStr.replaceAll(",\\s*where", " where"); 174 | } 175 | if(METHOD.equals("insert") || METHOD.equals("insertForID")) { 176 | //清洗插入SQL中的空值 177 | // System.out.println("1111METHOD = " + METHOD); 178 | //System.out.println("sqlStr = " + sqlStr); 179 | sqlStr = nullFilterForInsert(sqlStr); 180 | //System.out.println("sqlStr = " + sqlStr); 181 | } 182 | 183 | 184 | return sqlStr; 185 | } 186 | 187 | 188 | private Object[] nullFinderBuilder(Object[] args) { 189 | Object o = args[0]; 190 | String sql = (String) o; 191 | Object[] argsP = (Object[]) args[1]; 192 | int j=0; 193 | for(int i=0;i0){ 206 | //System.out.println("清洗空值" + j); 207 | argsP = Arrays.stream(argsP).filter(x -> x != null).toArray(); 208 | } 209 | //System.out.println("sql = " + sql); 210 | sql = sql.replaceAll("~=~=~=~","?"); 211 | args[0]= sql; 212 | args[1]= argsP; 213 | return args; 214 | } 215 | 216 | private Object[] nullFinderBuilderInsertForID(Object[] args) { 217 | Object o = args[0]; 218 | String sql = (String) o; 219 | Object[] argsP = (Object[]) args[2]; 220 | int j=0; 221 | for(int i=0;i0){ 234 | //System.out.println("清洗空值" + j); 235 | argsP = Arrays.stream(argsP).filter(x -> x != null).toArray(); 236 | } 237 | //System.out.println("sql = " + sql); 238 | sql = sql.replaceAll("~=~=~=~","?"); 239 | args[0]= sql; 240 | args[2]= argsP; 241 | return args; 242 | } 243 | 244 | 245 | 246 | //////////mybitis数据库连接串serverTimezone=Asia/Shanghai,,,数据库设置set time_zone='+8:00';就没问题 247 | private String timeStamp2DateString(Timestamp timeStamp) { 248 | SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 249 | //fm.setTimeZone(TimeZone.getTimeZone("UTC")); 250 | return fm.format(timeStamp); 251 | } 252 | 253 | private String timeStamp2DateString(LocalDateTime localDateTime) { 254 | 255 | Timestamp timeStamp = new Timestamp(localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()); 256 | SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 257 | return fm.format(timeStamp); 258 | } 259 | 260 | private int formatTimeOfListMap(List> result) { 261 | 262 | int n = 0; 263 | for (LinkedHashMap m : result) { 264 | //System.out.println("m = " + m); 265 | //if(m==null) continue; 266 | 267 | n+=formatTimeOfObjectMap(m); 268 | 269 | } 270 | return n; 271 | } 272 | 273 | 274 | private int formatTimeOfObjectMap(LinkedHashMap result) { 275 | 276 | int n = 0; 277 | if(result==null) return 0; 278 | for (String k : result.keySet()) { 279 | //System.out.println(k + " : " + result.get(k)); 280 | //System.out.println(result.get(k).getClass().getName()); 281 | 282 | if (result.get(k) != null && "java.sql.Timestamp".equals(result.get(k).getClass().getName())) { 283 | result.put(k, timeStamp2DateString((Timestamp) result.get(k))); 284 | n++; 285 | } 286 | if (result.get(k) != null && "java.sql.Date".equals(result.get(k).getClass().getName())) { 287 | result.put(k, result.get(k).toString()); 288 | n++; 289 | } 290 | if (result.get(k) != null && "java.sql.Time".equals(result.get(k).getClass().getName())) { 291 | result.put(k, result.get(k).toString()); 292 | n++; 293 | } 294 | if (result.get(k) != null && "java.time.LocalDateTime".equals(result.get(k).getClass().getName())) { 295 | result.put(k, timeStamp2DateString((LocalDateTime) result.get(k))); 296 | n++; 297 | } 298 | } 299 | 300 | 301 | return n; 302 | } 303 | 304 | 305 | public String nullFilterForInsert(String str) { 306 | String[] list1= str.split("\\)\\,\\s*\\("); 307 | String[] list2= str.split("\\)\\s+(values|VALUES)"); 308 | if(!(list1.length ==1 && list2.length==2)){return str;} 309 | 310 | String[] strOldList = str.trim().split("[(|)]",-1); 311 | if(strOldList.length!=5){return str;} 312 | 313 | String[] columnList = strOldList[1].trim().split("\\s*\\,\\s*"); 314 | String[] valuesList = strOldList[3].trim().split("\\s*\\,\\s*"); 315 | if(columnList.length != valuesList.length){return str;} 316 | String columnsNew = ""; 317 | String valuesNew = ""; 318 | for (int i = 0; i < columnList.length; i++) { 319 | if(!valuesList[i].equals("null")){ 320 | columnsNew+=columnList[i]+","; 321 | valuesNew+=valuesList[i]+","; 322 | } 323 | } 324 | columnsNew = columnsNew.substring(0, columnsNew.length() - 1); 325 | valuesNew = valuesNew.substring(0, valuesNew.length() - 1); 326 | String reStr = strOldList[0] + "("+columnsNew+") "+strOldList[2]+"("+valuesNew+")"; 327 | return reStr; 328 | } 329 | 330 | } 331 | -------------------------------------------------------------------------------- /CRUDTask.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.trigger.schedule; 2 | 3 | 4 | import com.example.demo.mapper.BaseDAO; 5 | import com.example.demo.mapper.BaseMapper; 6 | import com.example.demo.trigger.filter.ApiAccessFilter; 7 | import com.example.demo.util.JDBCUtil; 8 | import com.example.demo.util.ParamUtil; 9 | import com.example.demo.util.TimeUtil; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.scheduling.annotation.EnableScheduling; 12 | import org.springframework.scheduling.annotation.Scheduled; 13 | import org.springframework.web.bind.annotation.RequestParam; 14 | 15 | import javax.annotation.Resource; 16 | import java.util.*; 17 | 18 | @Configuration //1.主要用于标记配置类,兼备Component的效果。 19 | @EnableScheduling // 2.开启定时任务 20 | public class CRUDTask { 21 | 22 | @Resource 23 | private BaseMapper baseMapper; 24 | 25 | //3.添加定时任务 26 | @Scheduled(cron = "0/60 * * * * ?") 27 | //@Scheduled(cron = "0 5 0 * * ?")每天00:05:00执行 28 | //或直接指定时间间隔,例如:5秒 29 | //@Scheduled(fixedRate=5000) 30 | private void configureTasks() { 31 | 32 | System.err.println("1执行静态定时任务时间: " + TimeUtil.getCurrentDateStringMillisecond()); 33 | System.out.println("----------定时器2:>" + ApiAccessFilter.getProcessID() +" "+Thread.currentThread().getId() + " " + Thread.currentThread().getName()); 34 | 35 | try { 36 | long start = System.currentTimeMillis(); //获取开始时间 37 | String currentDateString = TimeUtil.getCurrentDateString(); 38 | 39 | String name = "王五"; 40 | Integer number = 70; 41 | String password = "sss"; 42 | 43 | Integer id = 3; 44 | Integer id1 = 10; 45 | 46 | int result = 0 ; 47 | 48 | 49 | /* //直接使用baseMapper 50 | result = baseMapper.insert("INSERT INTO user(name,password,number,time) " + 51 | " VALUES(#{args[0]},#{args[1]},#{args[2]},#{args[3]})",name,password,number,currentDateString); 52 | 53 | String sql = "INSERT INTO user(name,password,number,time) " + 54 | " VALUES(#{args[0]},#{args[1]},#{args[2]},#{args[3]})"; 55 | Map map = new HashMap(); 56 | 57 | result = baseMapper.insertForID(sql,map, name, password, number, currentDateString); 58 | System.out.println("id = " + map.get("id")); 59 | 60 | result = baseMapper.update("update user set name=#{args[0]},password=#{args[1]},number=#{args[2]} where id=#{args[3]}",name,password,number,id1); 61 | 62 | result = baseMapper.delete("delete from user where id=#{args[0]}",id); 63 | 64 | LinkedHashMap resultObject = baseMapper.get("SELECT * FROM user where id=#{args[0]}",id1); 65 | 66 | List> resultList = baseMapper.select("SELECT * FROM user where 1=1 and name=#{args[0]} and password=#{args[1]} and number=#{args[2]} ORDER BY #{args[3]} asc LIMIT 2,2",name,password,number,"time"); 67 | 68 | long resultCount = baseMapper.count("SELECT count(*) FROM user where 1=1 and name=#{args[0]} and password=#{args[1]} and number=#{args[2]}",name,password,number); 69 | 70 | Map map1 = new HashMap(); 71 | Integer a = 2; 72 | Integer b = 4; 73 | List> resultList1 = baseMapper.call("add_num(#{args[0]},#{args[1]},#{map.c,mode=OUT,jdbcType=BIGINT})",map1,a,b); 74 | System.out.println("map1 = " + map1); 75 | System.out.println("resultList1 = " + resultList1); 76 | 77 | result = baseMapper.execute("Truncate Table log"); 78 | System.out.println("result = " + result);*/ 79 | 80 | 81 | //使用baseMapper(LogTrackAspect) 82 | result = baseMapper.insert("INSERT INTO user(name,password,number,time) " + 83 | " VALUES(?,?,?,?)",name,password,number,currentDateString); 84 | 85 | Map map = new HashMap(); 86 | result = baseMapper.insertForID("INSERT INTO user(name,password,number,time) " + 87 | " VALUES(?,?,?,?)",map, name,password,number,currentDateString); 88 | System.out.println("id = " + map.get("id")); 89 | 90 | result = baseMapper.update("update user set name=?,password=?,number=? where id=?",name,password,number,id1); 91 | 92 | result = baseMapper.delete("delete from user where id=?",id); 93 | 94 | LinkedHashMap resultObject = baseMapper.get("SELECT * FROM user where id=?",id1); 95 | 96 | List> resultList = baseMapper.select("SELECT * FROM user where 1=1 and name=? and password=? and number=? ORDER BY ? asc LIMIT 2,2",name,password,number,"time"); 97 | 98 | long resultCount = baseMapper.count("SELECT count(*) FROM user where 1=1 and name=? and password=? and number=?",name,password,number); 99 | 100 | Map map1 = new HashMap(); 101 | Integer a = 2; 102 | Integer b = 4; 103 | List> resultList1 = baseMapper.call("add_num(?,?,#{map.c,mode=OUT,jdbcType=BIGINT})",map1,a,b); 104 | System.out.println("map1 = " + map1); 105 | System.out.println("resultList1 = " + resultList1); 106 | 107 | 108 | List sql = new ArrayList(); 109 | for (int i = 0; i < 10; i++) { 110 | sql.add("INSERT INTO user(name,password,number,time) VALUES('王五','sss',70,'" + currentDateString + "')"); 111 | 112 | } 113 | // String sql = "INSERT INTO user(name,password,number,time) VALUES('王五','sss',70,'" + currentDateString + "')"; 114 | // for (int i = 0; i < 20000; i++) { 115 | // sql += ",('王五','sss',70,'" + currentDateString + "')"; 116 | // 117 | // } 118 | System.out.println("size:" + sql.size()); 119 | int re = baseMapper.executeBatch(sql); 120 | System.out.println("re = " + re); 121 | 122 | 123 | 124 | result= baseMapper.execute("Truncate Table log"); 125 | System.out.println("result = " + result); 126 | 127 | 128 | 129 | long end = System.currentTimeMillis(); //获取结束时间 130 | System.out.println("111程序运行时间: " + (end - start) + "ms"); 131 | 132 | 133 | Thread.sleep(3000); 134 | } catch (InterruptedException e) { 135 | e.printStackTrace(); 136 | } 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /GenerateFromDB.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.util; 2 | 3 | import io.swagger.annotations.ApiImplicitParam; 4 | 5 | import java.util.LinkedHashMap; 6 | import java.util.List; 7 | 8 | public class GenerateFromDB { 9 | 10 | ///这里的字段描述查询语句需要修改 11 | List> result = JDBCUtil.select("desc user"); 12 | 13 | private String getInterPara() { 14 | 15 | 16 | 17 | System.out.println("原始数据库字段信息:"+result+"\n"); 18 | 19 | String reString = ""; 20 | 21 | for (LinkedHashMap m : result) { 22 | 23 | String f = (String) m.get("Field"); 24 | String t = (String) m.get("Type"); 25 | 26 | //System.out.println(f+"-->"+t); 27 | ///这里的类型对应关系有的数据库需要修改 28 | String type = ""; 29 | if(t.contains("bigint")){ 30 | type = "Long"; 31 | }else if(t.contains("smallint")){ 32 | type = "Short"; 33 | }else if(t.contains("int")){ 34 | type = "Integer"; 35 | }else if(t.contains("double")){ 36 | type = "Double"; 37 | }else if(t.contains("float")){ 38 | type = "Float"; 39 | }else if(t.contains("varchar")){ 40 | type = "String"; 41 | }else if(t.contains("text")){ 42 | type = "String"; 43 | }else if(t.contains("json")){ 44 | type = "String"; 45 | }else if(t.contains("datetime")){ 46 | type = "String"; 47 | }else{ 48 | 49 | } 50 | if(f.equals("id")){ 51 | reString += "@RequestParam(\""+f+"\")"+type+" "+f+","+"\n"; 52 | }else{ 53 | reString += "@RequestParam(name=\""+f+"\",required = false)"+type+" "+f+","+"\n"; 54 | } 55 | 56 | //System.out.println("@RequestParam(name=\""+f+"\",required = false)"+type+" "+f+","); 57 | } 58 | 59 | return reString; 60 | } 61 | 62 | 63 | private String getParaList() { 64 | 65 | //System.out.println("result:"+result); 66 | 67 | String reString = ""; 68 | 69 | for (LinkedHashMap m : result) { 70 | String f = (String) m.get("Field"); 71 | String t = (String) m.get("Type"); 72 | if(f.equals("id"))continue; 73 | reString += ""+f+","; 74 | //System.out.println("@RequestParam(name=\""+f+"\",required = false)"+type+" "+f+","); 75 | } 76 | 77 | 78 | return reString.substring(0, reString.length()-1)+"\n"; 79 | } 80 | 81 | private String getTypeParaList() { 82 | 83 | //System.out.println("result:"+result); 84 | 85 | String reString = ""; 86 | 87 | for (LinkedHashMap m : result) { 88 | String f = (String) m.get("Field"); 89 | String t = (String) m.get("Type"); 90 | if(f.equals("id"))continue; 91 | 92 | String type = ""; 93 | if(t.contains("bigint")){ 94 | type = "Long"; 95 | }else if(t.contains("smallint")){ 96 | type = "Short"; 97 | }else if(t.contains("int")){ 98 | type = "Integer"; 99 | }else if(t.contains("double")){ 100 | type = "Double"; 101 | }else if(t.contains("float")){ 102 | type = "Float"; 103 | }else if(t.contains("varchar")){ 104 | type = "String"; 105 | }else if(t.contains("text")){ 106 | type = "String"; 107 | }else if(t.contains("json")){ 108 | type = "String"; 109 | }else if(t.contains("datetime")){ 110 | type = "String"; 111 | }else{ 112 | 113 | } 114 | 115 | reString += type+" "+f+","; 116 | //System.out.println("@RequestParam(name=\""+f+"\",required = false)"+type+" "+f+","); 117 | } 118 | 119 | 120 | return reString.substring(0, reString.length()-1)+"\n"; 121 | } 122 | 123 | 124 | private String getUptFilter() { 125 | //System.out.println("result:"+result); 126 | String reString = ""; 127 | 128 | for (LinkedHashMap m : result) { 129 | 130 | String f = (String) m.get("Field"); 131 | String t = (String) m.get("Type"); 132 | if(f.equals("id"))continue; 133 | if(t.contains("bigint") || t.contains("int")){ 134 | reString += "if("+f+" != null && "+f+"!=-1){sqlStr += \""+f+"=\"+"+f+"+\",\";}"+"\n"; 135 | }else{ 136 | reString += "if("+f+" != null && !\"\".equals("+f+")){sqlStr += \""+f+"='\"+"+f+"+\"',\";}"+"\n"; 137 | } 138 | 139 | } 140 | return reString; 141 | } 142 | 143 | private String getSelectFilter() { 144 | //System.out.println("result:"+result); 145 | String reString = ""; 146 | 147 | for (LinkedHashMap m : result) { 148 | 149 | String f = (String) m.get("Field"); 150 | String t = (String) m.get("Type"); 151 | if(f.equals("id"))continue; 152 | if(t.contains("bigint") || t.contains("int")){ 153 | reString += "if("+f+" != null && "+f+"!=-1){sqlStr += \"and "+f+"=\"+"+f+"+\",\";}"+"\n"; 154 | }else{ 155 | reString += "if("+f+" != null && !\"\".equals("+f+")){sqlStr += \"and "+f+"='\"+"+f+"+\"',\";}"+"\n"; 156 | } 157 | 158 | } 159 | return reString; 160 | } 161 | 162 | 163 | private String getUptFilterWithoutIf() { 164 | //System.out.println("result:"+result); 165 | String reString = ""; 166 | 167 | for (LinkedHashMap m : result) { 168 | 169 | String f = (String) m.get("Field"); 170 | String t = (String) m.get("Type"); 171 | if(f.equals("id"))continue; 172 | if(t.contains("bigint") || t.contains("int")){ 173 | reString += ""+f+"=\"+"+f+"+\","; 174 | }else{ 175 | reString += ""+f+"='\"+"+f+"+\"',"; 176 | } 177 | 178 | } 179 | return reString; 180 | } 181 | 182 | private String getSelectFilterWithoutIf() { 183 | //System.out.println("result:"+result); 184 | String reString = ""; 185 | 186 | for (LinkedHashMap m : result) { 187 | 188 | String f = (String) m.get("Field"); 189 | String t = (String) m.get("Type"); 190 | if(f.equals("id"))continue; 191 | if(t.contains("bigint") || t.contains("int")){ 192 | reString += " and "+f+"=\"+"+f+"+\""; 193 | }else{ 194 | reString += " and "+f+"='\"+"+f+"+\"'"; 195 | } 196 | 197 | } 198 | return reString; 199 | } 200 | 201 | 202 | private String getUptFilterWithoutIfPre() { 203 | //System.out.println("result:"+result); 204 | String reString = ""; 205 | 206 | for (LinkedHashMap m : result) { 207 | 208 | String f = (String) m.get("Field"); 209 | String t = (String) m.get("Type"); 210 | if(f.equals("id"))continue; 211 | if(t.contains("bigint") || t.contains("int")){ 212 | reString += ""+f+"=?,"; 213 | }else{ 214 | reString += ""+f+"=?,"; 215 | } 216 | 217 | } 218 | return reString; 219 | } 220 | 221 | private String getSelectFilterWithoutIfPre() { 222 | //System.out.println("result:"+result); 223 | String reString = ""; 224 | 225 | for (LinkedHashMap m : result) { 226 | 227 | String f = (String) m.get("Field"); 228 | String t = (String) m.get("Type"); 229 | if(f.equals("id"))continue; 230 | if(t.contains("bigint") || t.contains("int")){ 231 | reString += " and "+f+"=?"; 232 | }else{ 233 | reString += " and "+f+"=?"; 234 | } 235 | 236 | } 237 | return reString; 238 | } 239 | 240 | private String getPostPara() { 241 | //System.out.println("result:"+result); 242 | String reString = ""; 243 | 244 | for (LinkedHashMap m : result) { 245 | 246 | String f = (String) m.get("Field"); 247 | String t = (String) m.get("Type"); 248 | if(f.equals("id"))continue; 249 | if(t.contains("bigint") || t.contains("int")){ 250 | reString += "paramMap.put(\""+f+"\",1);"+"\n"; 251 | }else if(t.contains("datetime")){ 252 | reString += "paramMap.put(\""+f+"\",\"2023-05-30 03:58:58\");"+"\n"; 253 | }else{ 254 | reString += "paramMap.put(\""+f+"\",\"a\");"+"\n"; 255 | } 256 | 257 | } 258 | return reString; 259 | } 260 | 261 | private String getSwaggerPara() { 262 | //System.out.println("result:"+result); 263 | String reString = ""; 264 | 265 | for (LinkedHashMap m : result) { 266 | 267 | String f = (String) m.get("Field"); 268 | String t = (String) m.get("Type"); 269 | if(f.equals("id"))continue; 270 | if(t.contains("bigint") || t.contains("int")){ 271 | reString += "@ApiImplicitParam(name=\""+f+"\",defaultValue=\"1\"),"+"\n"; 272 | }else if(t.contains("datetime")){ 273 | reString += "@ApiImplicitParam(name=\""+f+"\",defaultValue=\"2023-05-30 03:58:58\"),"+"\n"; 274 | }else{ 275 | reString += "@ApiImplicitParam(name=\""+f+"\",defaultValue=\"aaa\"),"+"\n"; 276 | } 277 | 278 | } 279 | return reString; 280 | 281 | } 282 | 283 | public static void main(String[] args) { 284 | 285 | 286 | 287 | String para1String = new GenerateFromDB().getInterPara(); 288 | System.out.println("接口参数列表(区分了id非空) = " + "\n" + para1String); 289 | 290 | 291 | 292 | 293 | String paraList = new GenerateFromDB().getParaList(); 294 | System.out.println("新增接口使用的参数列表串(过滤了id) = " + "\n" + paraList); 295 | 296 | String typeParaList = new GenerateFromDB().getTypeParaList(); 297 | System.out.println("新增接口使用的参数列表串(过滤了id) = " + "\n" + typeParaList); 298 | 299 | String uptFilter = new GenerateFromDB().getUptFilter(); 300 | System.out.println("修改接口使用的参数过滤语句(过滤了id) = " + "\n" + uptFilter); 301 | 302 | String selectFilter = new GenerateFromDB().getSelectFilter(); 303 | System.out.println("新增接口使用的参数列表串(过滤了id) = " + "\n" + selectFilter); 304 | 305 | String uptFilterWithoutIf = new GenerateFromDB().getUptFilterWithoutIf(); 306 | System.out.println("修改接口使用的参数过滤语句(过滤了id)(单句无需if) = " + "\n" + uptFilterWithoutIf+ "\n"); 307 | 308 | String selectFilterWithoutIf = new GenerateFromDB().getSelectFilterWithoutIf(); 309 | System.out.println("查询接口使用的参数列表串(过滤了id)(单句无需if) = " + "\n" + selectFilterWithoutIf+ "\n"); 310 | 311 | String uptFilterWithoutIfPre = new GenerateFromDB().getUptFilterWithoutIfPre(); 312 | System.out.println("修改接口使用的参数过滤语句(过滤了id)(单句无需if)(占位符) = " + "\n" + uptFilterWithoutIfPre+ "\n"); 313 | 314 | String selectFilterWithoutIfPre = new GenerateFromDB().getSelectFilterWithoutIfPre(); 315 | System.out.println("查询接口使用的参数列表串(过滤了id)(单句无需if)(占位符) = " + "\n" + selectFilterWithoutIfPre+ "\n"); 316 | 317 | String postPara = new GenerateFromDB().getPostPara(); 318 | System.out.println("测试客户请求参数(过滤了id) = " + "\n" + postPara); 319 | 320 | String swaggerPara = new GenerateFromDB().getSwaggerPara(); 321 | System.out.println("Swagger测试请求参数(过滤了id) = " + "\n" + swaggerPara); 322 | 323 | 324 | } 325 | 326 | 327 | } -------------------------------------------------------------------------------- /JDBCUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.util; 2 | 3 | 4 | import cn.hutool.json.JSONArray; 5 | import cn.hutool.json.JSONUtil; 6 | import org.javatuples.Triplet; 7 | 8 | import java.sql.*; 9 | import java.time.LocalDateTime; 10 | import java.time.ZoneOffset; 11 | import java.util.*; 12 | 13 | public class JDBCUtil { 14 | public static Connection conn = getConnection(); 15 | 16 | public static Connection getConnection() { 17 | try { 18 | long start=System.currentTimeMillis(); //获取开始时间 19 | //Class.forName("com.mysql.jdbc.Driver"); // 加载MySQL数据库驱动 20 | Class.forName("com.mysql.cj.jdbc.Driver"); // 加载MySQL数据库驱动 21 | 22 | System.out.println("数据库驱动加载成功!!"); 23 | String url = "jdbc:mysql://192.168.*.*:3306/user?serverTimezone=UTC&useSSL=false&allowMultiQueries=true"; // 定义与连接数据库的url 24 | String user = "root"; // 定义连接数据库的用户名 上面 不加 ?useSSL=false 会有警告 大概的意思就是说建立ssl连接,但是服务器没有身份认证,这种方式不推荐使用。 25 | String passWord = ""; // 定义连接数据库的密码 26 | conn = DriverManager.getConnection(url, user, passWord); // 连接连接 27 | System.out.println("已成功的与MySQL数据库建立连接!!"); 28 | long end=System.currentTimeMillis(); //获取结束时间 29 | System.out.println("程序运行时间(连接): "+(end-start)+"ms"); 30 | } catch (Exception e) { 31 | e.printStackTrace(); 32 | } 33 | return conn; 34 | } 35 | 36 | 37 | public static Timestamp localDateTime2TimeStamp(LocalDateTime localDateTime) { 38 | 39 | Timestamp timeStamp = new Timestamp(localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()); 40 | return timeStamp; 41 | 42 | } 43 | 44 | 45 | public static List> rs2list(ResultSet rs) { 46 | List> result = new ArrayList>(); 47 | try { 48 | ResultSetMetaData md = rs.getMetaData(); //获得结果集结构信息,元数据 49 | int columnCount = md.getColumnCount(); //获得列数 50 | while (rs.next()) { 51 | LinkedHashMap rowData = new LinkedHashMap(); 52 | for (int i = 1; i <= columnCount; i++) { 53 | if(rs.getObject(i) == null) continue; 54 | //System.out.println(md.getColumnName(i)+"*:"+md.getColumnTypeName(i)+":"+md.getColumnClassName(i)); 55 | //System.out.println(rs.getObject(i) + "*=" + rs.getObject(i).getClass().getName()); 56 | Object tmp = null; 57 | if("java.sql.Timestamp".equals(md.getColumnClassName(i))){ 58 | tmp=localDateTime2TimeStamp((LocalDateTime) rs.getObject(i)); 59 | }else{ 60 | tmp=rs.getObject(i); 61 | } 62 | if(rowData.containsKey(md.getColumnName(i))){ 63 | if(rowData.containsKey(md.getColumnName(i)+"_rename")){ 64 | rowData.put(md.getColumnName(i)+"_rename_rename", tmp); 65 | }else{ 66 | rowData.put(md.getColumnName(i)+"_rename", tmp); 67 | } 68 | }else{ 69 | rowData.put(md.getColumnName(i), tmp); 70 | } 71 | 72 | } 73 | result.add(rowData); 74 | 75 | } 76 | } catch (Exception e) { 77 | e.printStackTrace(); 78 | } 79 | return result; 80 | } 81 | 82 | public static PreparedStatement prepareStatement(String sql){ 83 | PreparedStatement pstmt = null; 84 | try { 85 | if(!conn.isValid(5)){ 86 | getConnection(); 87 | } 88 | pstmt = conn.prepareStatement(sql); 89 | } catch (Exception e) { 90 | e.printStackTrace(); 91 | } 92 | return pstmt; 93 | 94 | } 95 | 96 | public static List> select(String sql,Object ...args){ 97 | List> result = new ArrayList>(); 98 | try { 99 | if(!conn.isValid(5)){ 100 | getConnection(); 101 | } 102 | PreparedStatement stmt = conn.prepareStatement(sql); 103 | for(int i=0;i get(String sql,Object ...args){ 115 | LinkedHashMap result = new LinkedHashMap(); 116 | try { 117 | if(!conn.isValid(5)){ 118 | getConnection(); 119 | } 120 | PreparedStatement stmt = conn.prepareStatement(sql); 121 | for(int i=0;i sql){ 207 | int[] rs = new int[0]; 208 | int success = 0; 209 | try { 210 | if(!conn.isValid(5)){ 211 | getConnection(); 212 | } 213 | Statement stmt = conn.createStatement(); 214 | 215 | for (String s : sql) { 216 | stmt.addBatch(s); 217 | //System.out.println("addBatch:"+s); 218 | } 219 | rs = stmt.executeBatch(); 220 | for (int r : rs) { 221 | success+=r; 222 | } 223 | 224 | } catch (Exception e) { 225 | e.printStackTrace(); 226 | } 227 | return success; 228 | } 229 | 230 | 231 | public static int executeTransaction(List sql){ 232 | int rs = 0; 233 | try { 234 | if(!conn.isValid(5)){ 235 | getConnection(); 236 | } 237 | conn.setAutoCommit(false); 238 | Statement stmt = conn.createStatement(); 239 | 240 | for (String s : sql) { 241 | stmt.execute(s); 242 | System.out.println("addExecute:"+s); 243 | } 244 | stmt.close(); 245 | conn.commit(); 246 | 247 | rs = 1; 248 | 249 | } catch (Exception e) { 250 | e.printStackTrace(); 251 | try { 252 | //遇到异常,则回滚事务 253 | conn.rollback(); 254 | } catch (SQLException e1) { 255 | e1.printStackTrace(); 256 | } 257 | rs = 0; 258 | }finally { 259 | try { 260 | 261 | conn.setAutoCommit(true); 262 | //conn.close(); 263 | 264 | } catch (SQLException e) { 265 | e.printStackTrace(); 266 | } 267 | 268 | } 269 | 270 | return rs; 271 | 272 | } 273 | 274 | public static int update(String sql,Object ...args){ 275 | return insert(sql,args); 276 | } 277 | 278 | public static int delete(String sql,Object ...args){ 279 | return insert(sql,args); 280 | } 281 | 282 | public static int execute(String sql,Object ...args){ 283 | int rs = 0; 284 | try { 285 | if(!conn.isValid(5)){ 286 | getConnection(); 287 | } 288 | 289 | PreparedStatement stmt = conn.prepareStatement(sql); 290 | for(int i=0;i> call(String sql,Map map,Object ...args){ 304 | List> result = new ArrayList>(); 305 | try { 306 | if(!conn.isValid(5)){ 307 | getConnection(); 308 | } 309 | 310 | CallableStatement stmt = conn.prepareCall("call "+sql); 311 | List tripletList = (List) map.get("tripletList"); 312 | List outIndex = new ArrayList(); 313 | if(tripletList == null || tripletList.size()==0){ 314 | 315 | System.out.println("没有OUT参数"); 316 | }else{ 317 | for (Triplet triplet : tripletList) { 318 | stmt.registerOutParameter((int)triplet.getValue(1), (int)triplet.getValue(2)); 319 | outIndex.add((int)triplet.getValue(1)); 320 | } 321 | 322 | } 323 | for(int i=0;i> result = JDBCUtil.select("SELECT * FROM user where 1=1 and name = ? LIMIT 10", "武风华"); 363 | // List> result = JDBCUtil.select("SELECT * FROM user where 1=1 and name = '武风华' LIMIT 10"); 364 | // //System.out.println("result = " + result); 365 | // JSONArray array = JSONUtil.parseArray(result); 366 | // System.out.println("array.toString() = " + array.toJSONString(4)); 367 | 368 | 369 | // LinkedHashMap result = JDBCUtil.get("SELECT * FROM user where 1=1 and name = ? LIMIT 10", "武风华"); 370 | // //System.out.println("result = " + result); 371 | // JSONObject array = JSONUtil.parseObj(result); 372 | // System.out.println("array.toString() = " + array.toJSONString(4)); 373 | 374 | 375 | // long result = JDBCUtil.count("SELECT count(*) FROM user where 1=1 and name = ?","武风华"); 376 | // System.out.println("result = " + result); 377 | 378 | // int result = JDBCUtil.delete("delete from user where id=?",3); 379 | // System.out.println("result = " + result); 380 | 381 | // int result= JDBCUtil.update("update user set name=? where id = ?","王五改",6); 382 | // System.out.println("result = " + result); 383 | 384 | // int result= JDBCUtil.insert("INSERT INTO user(name,password,number,time) VALUES(?,'sss',70,'"+currentDateString+"')","王五新"); 385 | // System.out.println("result = " + result); 386 | 387 | // Map map = new HashMap(); 388 | // int result = JDBCUtil.insertForID("INSERT INTO user(name,password,number,time) " + 389 | // " VALUES(?,?,?,?)",map, "王五","sss",70, currentDateString); 390 | // System.out.println("id = " + map.get("id")); 391 | 392 | 393 | // int result= JDBCUtil.execute("Truncate Table log"); 394 | // System.out.println("result = " + result); 395 | 396 | 397 | /* List sql = new ArrayList(); 398 | for (int i = 0; i < 1000; i++) { 399 | sql.add("INSERT INTO user(name,password,number,time) VALUES('王五','sss',70,'" + currentDateString + "')"); 400 | 401 | } 402 | 403 | // String sql = "INSERT INTO user(name,password,number,time) VALUES('王五','sss',70,'" + currentDateString + "')"; 404 | // for (int i = 0; i < 20000; i++) { 405 | // sql += ",('王五','sss',70,'" + currentDateString + "')"; 406 | // 407 | // } 408 | System.out.println("size:" + sql.size()); 409 | int re = JDBCUtil.executeBatch(sql); 410 | System.out.println("re = " + re);*/ 411 | 412 | 413 | 414 | 415 | /* List tripletList = new ArrayList(); 416 | tripletList.add(Triplet.with("c", 3, Types.BIGINT)); 417 | Map map1 = new HashMap(); 418 | map1.put("tripletList",tripletList); 419 | Integer a = 2; 420 | Integer b = 4; 421 | List> resultList1 = JDBCUtil.call("add_num(?,?,?)",map1,a,b); 422 | System.out.println("map1 = " + map1); 423 | System.out.println("resultList1 = " + resultList1);*/ 424 | 425 | //////////////////////////////////可变参数PreparedStatement/////////////////////////////////////// 426 | 427 | 428 | 429 | 430 | //System.out.println("result:"+result); 431 | long end = System.currentTimeMillis(); //获取结束时间 432 | System.out.println("程序运行时间: " + (end - start) + "ms"); 433 | 434 | } catch (Exception e) { 435 | e.printStackTrace(); 436 | } 437 | //System.out.println("result:"+Arrays.toString(re)); 438 | 439 | } 440 | } 441 | -------------------------------------------------------------------------------- /JDBCUtilHikari.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.util; 2 | 3 | import com.gbase.jdbc.StatementImpl; 4 | import com.zaxxer.hikari.HikariConfig; 5 | import com.zaxxer.hikari.HikariDataSource; 6 | import com.zaxxer.hikari.HikariPoolMXBean; 7 | 8 | import java.sql.*; 9 | import java.time.LocalDateTime; 10 | import java.time.ZoneOffset; 11 | import java.util.ArrayList; 12 | import java.util.LinkedHashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | public class JDBCUtilHikari { 17 | public static HikariDataSource dataSource = initConnection(); 18 | 19 | 20 | 21 | public static String poolState() { 22 | String poolName = dataSource.getPoolName(); 23 | HikariPoolMXBean mx = dataSource.getHikariPoolMXBean(); 24 | String format = String.format("%s - stats (total=%d, active=%d, idle=%d, waiting=%d)",poolName,mx.getTotalConnections(), mx.getActiveConnections(), mx.getIdleConnections(), mx.getThreadsAwaitingConnection()); 25 | return format; 26 | } 27 | 28 | 29 | //////Hikari连接池版本////////////// 30 | public static HikariDataSource initConnection() { 31 | HikariDataSource ds = null; 32 | try { 33 | long start = System.currentTimeMillis(); //获取开始时间 34 | System.out.println("数据库驱动加载成功!!"); 35 | String url = "jdbc:mysql://192.168.*.*:3306/user?serverTimezone=UTC&useSSL=false&allowMultiQueries=true"; // 定义与连接数据库的url 36 | String user = "root"; // 定义连接数据库的用户名 上面 不加 ?useSSL=false 会有警告 大概的意思就是说建立ssl连接,但是服务器没有身份认证,这种方式不推荐使用。 37 | String passWord = ""; // 定义连接数据库的密码 38 | HikariConfig hikariConfig = new HikariConfig(); 39 | hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver"); 40 | //设置url 41 | hikariConfig.setJdbcUrl(url); 42 | //数据库帐号 43 | hikariConfig.setUsername(user); 44 | //数据库密码 45 | hikariConfig.setPassword(passWord); 46 | hikariConfig.addDataSourceProperty("cachePrepStmts", "true"); 47 | hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250"); 48 | hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); 49 | //hikariConfig.setIdleTimeout(1000); 50 | hikariConfig.setAutoCommit(true); 51 | //hikariConfig.setMaxLifetime(5000); 52 | hikariConfig.setMinimumIdle(10); 53 | hikariConfig.setMaximumPoolSize(1000); 54 | ds = new HikariDataSource(hikariConfig); 55 | //conn = ds.getConnection(); 56 | System.out.println("已成功的与Gabse 8A数据库建立连接!!"); 57 | long end = System.currentTimeMillis(); //获取结束时间 58 | System.out.println("程序运行时间(连接): " + (end - start) + "ms"); 59 | } catch (Exception e) { 60 | e.printStackTrace(); 61 | } 62 | return ds; 63 | } 64 | 65 | 66 | public static Timestamp localDateTime2TimeStamp(LocalDateTime localDateTime) { 67 | 68 | Timestamp timeStamp = new Timestamp(localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli()); 69 | return timeStamp; 70 | 71 | } 72 | 73 | 74 | public static List> rs2list(ResultSet rs) { 75 | List> result = new ArrayList>(); 76 | try { 77 | ResultSetMetaData md = rs.getMetaData(); //获得结果集结构信息,元数据 78 | int columnCount = md.getColumnCount(); //获得列数 79 | while (rs.next()) { 80 | LinkedHashMap rowData = new LinkedHashMap(); 81 | for (int i = 1; i <= columnCount; i++) { 82 | if(rs.getObject(i) == null) continue; 83 | //System.out.println(md.getColumnName(i)+"*:"+md.getColumnTypeName(i)+":"+md.getColumnClassName(i)); 84 | //System.out.println(rs.getObject(i) + "*=" + rs.getObject(i).getClass().getName()); 85 | Object tmp = null; 86 | if("java.time.LocalDateTime".equals(rs.getObject(i).getClass().getName())){ 87 | tmp=localDateTime2TimeStamp((LocalDateTime) rs.getObject(i)); 88 | 89 | }else{ 90 | tmp=rs.getObject(i); 91 | } 92 | //tmp=rs.getObject(i); 93 | if(rowData.containsKey(md.getColumnName(i))){ 94 | if(rowData.containsKey(md.getColumnName(i)+"_rename")){ 95 | rowData.put(md.getColumnName(i)+"_rename_rename", tmp); 96 | }else{ 97 | rowData.put(md.getColumnName(i)+"_rename", tmp); 98 | } 99 | }else{ 100 | rowData.put(md.getColumnName(i), tmp); 101 | } 102 | 103 | } 104 | result.add(rowData); 105 | 106 | } 107 | } catch (Exception e) { 108 | e.printStackTrace(); 109 | } 110 | return result; 111 | } 112 | 113 | 114 | public static Connection connection() { 115 | Connection conn = null; 116 | 117 | try { 118 | conn = dataSource.getConnection(); 119 | 120 | } catch (Exception e) { 121 | e.printStackTrace(); 122 | } 123 | return conn; 124 | 125 | } 126 | 127 | public static List> select(String sql,Object ...args){ 128 | List> result = new ArrayList>(); 129 | Connection conn = null; 130 | PreparedStatement stmt = null; 131 | try { 132 | 133 | conn = dataSource.getConnection(); 134 | System.out.println("conn = " + conn); 135 | stmt = conn.prepareStatement(sql); 136 | for(int i=0;i get(String sql,Object ...args){ 167 | LinkedHashMap result = new LinkedHashMap(); 168 | Connection conn = null; 169 | PreparedStatement stmt = null; 170 | try { 171 | 172 | conn = dataSource.getConnection(); 173 | System.out.println("conn = " + conn); 174 | stmt = conn.prepareStatement(sql); 175 | for(int i=0;i sql){ 323 | Connection conn = null; 324 | Statement stmt = null; 325 | int[] rs = new int[0]; 326 | int success = 0; 327 | try { 328 | 329 | conn = dataSource.getConnection(); 330 | System.out.println("conn = " + conn); 331 | stmt = conn.createStatement(); 332 | 333 | for (String s : sql) { 334 | stmt.addBatch(s); 335 | //System.out.println("addBatch:"+s); 336 | } 337 | rs = stmt.executeBatch(); 338 | for (int r : rs) { 339 | success+=r; 340 | } 341 | stmt.close(); 342 | conn.close(); 343 | } catch (Exception e) { 344 | e.printStackTrace(); 345 | } finally { 346 | try { 347 | stmt.close(); 348 | System.out.println("关闭stmt连接"); 349 | } catch (SQLException throwables) { 350 | throwables.printStackTrace(); 351 | } 352 | try { 353 | conn.close(); 354 | System.out.println("关闭conn连接"); 355 | } catch (SQLException throwables) { 356 | throwables.printStackTrace(); 357 | } 358 | } 359 | return success; 360 | } 361 | 362 | 363 | public static int executeTransaction(List sql){ 364 | Connection conn = null; 365 | Statement stmt = null; 366 | int rs = 0; 367 | try { 368 | 369 | conn = dataSource.getConnection(); 370 | 371 | conn.setAutoCommit(false); 372 | stmt = conn.createStatement(); 373 | 374 | for (String s : sql) { 375 | stmt.execute(s); 376 | System.out.println("addExecute:"+s); 377 | } 378 | stmt.close(); 379 | conn.commit(); 380 | 381 | rs = 1; 382 | conn.close(); 383 | } catch (Exception e) { 384 | e.printStackTrace(); 385 | try { 386 | //遇到异常,则回滚事务 387 | conn.rollback(); 388 | } catch (SQLException e1) { 389 | e1.printStackTrace(); 390 | } 391 | rs = 0; 392 | }finally { 393 | try { 394 | 395 | conn.setAutoCommit(true); 396 | try { 397 | stmt.close(); 398 | System.out.println("关闭stmt连接"); 399 | } catch (SQLException throwables) { 400 | throwables.printStackTrace(); 401 | } 402 | try { 403 | conn.close(); 404 | System.out.println("关闭conn连接"); 405 | } catch (SQLException throwables) { 406 | throwables.printStackTrace(); 407 | } 408 | 409 | } catch (SQLException e) { 410 | e.printStackTrace(); 411 | } 412 | 413 | } 414 | 415 | return rs; 416 | 417 | } 418 | 419 | public static int update(String sql,Object ...args){ 420 | return insert(sql,args); 421 | } 422 | 423 | public static int delete(String sql,Object ...args){ 424 | return insert(sql,args); 425 | } 426 | 427 | public static int execute(String sql,Object ...args){ 428 | Connection conn = null; 429 | PreparedStatement stmt = null; 430 | int rs = 0; 431 | try { 432 | conn = dataSource.getConnection(); 433 | System.out.println("conn = " + conn); 434 | stmt = conn.prepareStatement(sql); 435 | for(int i=0;i> call(String sql,Map map,Object ...args){ 464 | Connection conn = null; 465 | CallableStatement stmt = null; 466 | List> result = new ArrayList>(); 467 | try { 468 | conn = dataSource.getConnection(); 469 | System.out.println("conn = " + conn); 470 | stmt = conn.prepareCall("call "+sql); 471 | List tripletList = (List) map.get("tripletList"); 472 | List outIndex = new ArrayList(); 473 | if(tripletList == null || tripletList.size()==0){ 474 | 475 | System.out.println("没有OUT参数"); 476 | }else{ 477 | for (Triplet triplet : tripletList) { 478 | stmt.registerOutParameter((int)triplet.getValue(1), (int)triplet.getValue(2)); 479 | outIndex.add((int)triplet.getValue(1)); 480 | } 481 | 482 | } 483 | for(int i=0;i resultObject = baseMapper.get("SELECT * FROM user where id=?",id1); 18 | 19 | int result = baseMapper.insert("INSERT INTO user(name,password,number,time) VALUES(?,?,?,?)",name,password,number,currentDateString); 20 | 21 | int result = baseMapper.update("update user set name=?,password=?,number=? where id=?",name,password,number,id1); 22 | 23 | int result = baseMapper.delete("delete from user where id=?",id); 24 | 25 | int result= baseMapper.execute("Truncate Table log"); 26 | ``` 27 | 28 | ## 特点: 29 | 1. 无需为具体库表建立实体类和Mapper,统一使用BaseMapper即可 30 | 2. 采用弱类型返回结果集,这个返回值无需任何转换可以直接在SpringBoot的Controller里面做响应(一般也不需要Service) 31 | 3. 将controller、entity、mapper、service、resources简化为只要在controller接口里面直接写逻辑,每一组接口只要写一个java文件 32 | 4. 对DDL,DCL也很好的支持,适合大量动态建表的业务 33 | 5. 对复杂的联表查询,聚合查询支持很好,无需任何配置和定义,直接可以执行复杂查询SQL语句 34 | 6. 对存储过程支持友好,支持结果回传 35 | 7. BaseMapper将数据库操作抽象为10种,在JDBC语义和ORM语义间做了平衡,支持日常CRUD操作 36 | 8. 正常直接使用BaseMapper(带BaseMapperAspect装饰器)版本,另有一个单文件集成的原生JDBCUtil版本,两个版本接口的基本形式都是一样的 37 | 9. 支持JDBC中?占位符,跟原生JDBC的SQL占位符写法习惯一致,实际的值通过后面的可变参数传递 38 | 10. 在CRUDTask文件中可以查看调用示例 39 | 11. APITemplate文件是典型的CRUD接口逻辑代码,结合SQLBuilderUtil可以实现简单SQL语句的自动生成,结合AutoValueFromSqlUtil可以实现接口参数的自动填充 40 | 41 | ## 使用方式: 42 | 1. **试用方式:** 只需要集成1个BaseMapper文件即可,集成和使用方式跟正常的Mapper相同(在不使用?占位符和不需要时间格式化的情况下,跟正常模式接口完全一样) 43 | 2. **正常方式:** 集成2个BaseMapper\*文件即可,集成和使用方式跟正常的Mapper相同,BaseMapperAspect是装饰器(参数占位符加工和结果集时间格式化) 44 | 3. **备用方式:** 为在没有Mybatis的环境下使用该风格接口,直接用JDBC实现了原生版本,接口跟BaseMapper是一样的,这种方式只需要集成一个JDBCUtil文件即可,这个是单连接版本,对应的连接池版本可以使用JDBCUtilHikari.java 45 | 46 | ## 接口介绍: 47 | 1. **select:** 所有的结果集查询接口,直接拼SQL查询语句一行代码调用函数即可,返回值就是直接SpringBoot可以响应的格式(当然也可以加工后返回),无需bean,无需新建mapper,支持分组查询,连接查询,子查询,组合查询(UNION),视图查询,各种统计类的查询也直接用这个接口即可,别名as什么SpringBoot响应的json字段就是什么(也就是LinkedHashMap的key) 48 | 2. **count:** 所有的单值计数查询的快捷接口,也可以用于分页接口的总数接口,直接返回就是一个long型的数字,无需任何解析和加工 49 | 3. **get:** 所有的单对象点查询的快捷接口,返回的直接是一个对象(函数返回LinkedHashMap,SpringBoot响应json对象) 50 | 4. **insert:** 所有的插入语句接口,返回值是成功行数 51 | 5. **insertForID:** 所有的插入语句,支持获得被插入数据的主键ID值的版本,返回值是成功行数,主键ID值在map.id 52 | 6. **update:** 所有的更新语句接口,返回值是成功行数 53 | 7. **delete:** 所有的删除语句接口,返回值是成功行数 54 | 8. **execute:** 所有的执行语句接口,返回值是成功行数,支持所有的DDL,DCL语句,常用于建库建表,建用户,赋权等操作 55 | 9. **executeBatch:** 支持批处理的接口,可以一次执行多条语句 56 | 10. **call:** 支持调用存储过程的接口,支持带结果集存储过程,也支持带OUT参数 57 | 58 | ## 接口列表: 59 | 1. **select:** List> select(String sql,Object ...args) 60 | 2. **count:** long count(String sql,Object ...args) 61 | 3. **get:** LinkedHashMap get(String sql,Object ...args) 62 | 4. **insert:** int insert(String sql,Object ...args) 63 | 5. **insertForID:** int insertForID(String sql,Map map,Object ...args) 64 | 6. **update:** int update(String sql,Object ...args) 65 | 7. **delete:** int delete(String sql,Object ...args) 66 | 8. **execute:** int execute(String sql,Object ...args) 67 | 9. **executeBatch:** int executeBatch(List sql,Object ...args) 68 | 10. **call:** List> call(String sql,Map map,Object ...args) 69 | 70 | ## 联系人: 71 | 有问题可以联系:zhangchuang@iie.ac.cn 72 | -------------------------------------------------------------------------------- /RequestValue.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.commom; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import java.util.regex.Pattern; 5 | 6 | public class RequestValue { 7 | 8 | HttpServletRequest request; 9 | public RequestValue(HttpServletRequest request) { 10 | this.request=request; 11 | } 12 | 13 | /* 14 | * 判断是否为整数 15 | * @param str 传入的字符串 16 | * @return 是整数返回true,否则返回false 17 | */ 18 | public boolean isInteger(String str) { 19 | Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); 20 | return pattern.matcher(str).matches(); 21 | } 22 | 23 | public String getString(String s){ 24 | if(this.request.getParameter(s)==null) return null; 25 | return this.request.getParameter(s); 26 | } 27 | public Integer getInteger(String s){ 28 | if(this.request.getParameter(s)==null) return null; 29 | return Integer.valueOf(this.request.getParameter(s)); 30 | } 31 | public Long getLong(String s){ 32 | if(this.request.getParameter(s)==null) return null; 33 | return Long.valueOf(this.request.getParameter(s)); 34 | } 35 | 36 | public Short getShort(String s){ 37 | if(this.request.getParameter(s)==null) return null; 38 | return Short.valueOf(this.request.getParameter(s)); 39 | } 40 | 41 | public Float getFloat(String s){ 42 | if(this.request.getParameter(s)==null) return null; 43 | return Float.valueOf(this.request.getParameter(s)); 44 | } 45 | 46 | public Double getDouble(String s){ 47 | if(this.request.getParameter(s)==null) return null; 48 | return Double.valueOf(this.request.getParameter(s)); 49 | } 50 | 51 | public Object getObject(String s){ 52 | Object o = this.request.getParameter(s); 53 | if(o==null) return null; 54 | if(isInteger(o.toString())){ 55 | o=Integer.valueOf((String) o); 56 | } 57 | return o; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /SQLBuilderUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.util; 2 | 3 | import org.apache.kafka.common.protocol.types.Field; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import java.util.LinkedHashMap; 7 | import java.util.List; 8 | 9 | public class SQLBuilderUtil { 10 | 11 | 12 | static List> result = JDBCUtil.select("desc user"); 13 | public static String pageAndOrderBuilder(String sql,String orderColumn,String orderDirection, 14 | Integer pageNum,Integer pageSize) { 15 | 16 | if(pageNum == null) pageNum = 1; 17 | if(pageSize == null) pageSize = 10; 18 | String sqlOrderStr = ""; 19 | if (orderColumn != null && orderDirection != null) { 20 | sqlOrderStr = orderColumn + " " + orderDirection; 21 | } else { 22 | sqlOrderStr = "id desc"; 23 | } 24 | if(sqlOrderStr.equals("id desc") || sqlOrderStr.equals("id asc")){ 25 | }else{ 26 | sqlOrderStr += ", id desc"; 27 | } 28 | sql += " ORDER BY " + sqlOrderStr + " LIMIT " + (pageNum-1)*pageSize + ","+pageSize; 29 | return sql; 30 | } 31 | 32 | public static String pageAndOrderBuilder(String sql, HttpServletRequest request) { 33 | 34 | String orderColumn = request.getParameter("orderColumn"); 35 | String orderDirection = request.getParameter("orderDirection"); 36 | 37 | Integer pageNum = null; 38 | if(request.getParameter("pageNum") !=null) pageNum = Integer.valueOf(request.getParameter("pageNum")); 39 | Integer pageSize = null; 40 | if(request.getParameter("pageSize") !=null) pageSize = Integer.valueOf(request.getParameter("pageSize")); 41 | 42 | System.out.println("111pageNum = " + pageNum); 43 | System.out.println("111pageSize = " + pageSize); 44 | return pageAndOrderBuilder(sql,orderColumn,orderDirection,pageNum,pageSize); 45 | } 46 | 47 | public static String columns(String table) { 48 | 49 | String sql = ""; 50 | 51 | for (LinkedHashMap m : result) { 52 | String f = (String) m.get("Field"); 53 | String t = (String) m.get("Type"); 54 | if(f.equals("id"))continue; 55 | sql += ""+f+","; 56 | //System.out.println("@RequestParam(name=\""+f+"\",required = false)"+type+" "+f+","); 57 | } 58 | 59 | return sql.substring(0, sql.length()-1); 60 | 61 | } 62 | 63 | public static String typeColumns(String table) { 64 | 65 | String sql = ""; 66 | 67 | for (LinkedHashMap m : result) { 68 | String f = (String) m.get("Field"); 69 | String t = (String) m.get("Type"); 70 | if(f.equals("id"))continue; 71 | System.out.println("t = " + t); 72 | String type = ""; 73 | if(t.contains("bigint")){ 74 | type = "Long"; 75 | }else if(t.contains("smallint")){ 76 | type = "Short"; 77 | }else if(t.contains("int")){ 78 | type = "Integer"; 79 | }else if(t.contains("double")){ 80 | type = "Double"; 81 | }else if(t.contains("float")){ 82 | type = "Float"; 83 | }else if(t.contains("varchar")){ 84 | type = "String"; 85 | }else if(t.contains("text")){ 86 | type = "String"; 87 | }else if(t.contains("json")){ 88 | type = "String"; 89 | }else if(t.contains("datetime")){ 90 | type = "String"; 91 | }else{ 92 | 93 | } 94 | 95 | sql += type+" "+f+","; 96 | //System.out.println("@RequestParam(name=\""+f+"\",required = false)"+type+" "+f+","); 97 | } 98 | 99 | return sql.substring(0, sql.length()-1); 100 | } 101 | 102 | public static String deleteSQL(String table) { 103 | 104 | String sql = "delete from "+table+" where id=?"; 105 | return sql; 106 | } 107 | public static String insertSQL(String table, String columns) { 108 | 109 | String sql = "INSERT INTO "+table+"("+columns+") VALUES("+columns.replaceAll("\\w[-\\w.+]*","?")+")"; 110 | return sql; 111 | } 112 | 113 | public static String insertSQL(String table) { 114 | 115 | String columns = columns(table); 116 | String sql = insertSQL(table, columns); 117 | return sql; 118 | } 119 | public static String updateSQL(String table, String columns) { 120 | 121 | String sql = "update user set "+columns.replaceAll(",","=?,")+"=? where id=?"; 122 | return sql; 123 | } 124 | 125 | public static String updateSQL(String table) { 126 | String columns = columns(table); 127 | String sql = updateSQL(table, columns); 128 | return sql; 129 | } 130 | public static String getSQL(String table) { 131 | 132 | String sql = "SELECT * FROM "+table+" where id=?"; 133 | return sql; 134 | } 135 | public static String countSQL(String table, String where) { 136 | 137 | String sql = "SELECT count(*) FROM "+table+" where 1=1 and "+where; 138 | return sql; 139 | } 140 | public static String showSQL(String table, String where) { 141 | 142 | String sql = "SELECT * FROM "+table+" where 1=1 and "+where; 143 | return sql; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /test: -------------------------------------------------------------------------------- 1 | 11112345 2 | 22222 3 | 4 | 33333 5 | qqqq 6 | yyyyyy 7 | iiiiiii 8 | 1111 9 | eeeee 10 | 22222 11 | rrrrr 12 | 66666 13 | yyyyy 14 | 33333 15 | 22222 16 | -------------------------------------------------------------------------------- /test.config: -------------------------------------------------------------------------------- 1 | 这是生产环境的配置 2 | --------------------------------------------------------------------------------