/** * @date 2023/6/28 09:57 */ public class CustomDbPro extends DbPro { public CustomDbPro(String configName) { super(configName); }
@SuppressWarnings("rawtypes") @Override protected int[] batch(Config config, Connection conn, String sql, String columns, List list, int batchSize) throws SQLException { if (list == null || list.size() == 0) return new int[0]; Object element = list.get(0); if (!(element instanceof Record) && !(element instanceof Model)) throw new IllegalArgumentException("The element in list must be Model or Record."); if (batchSize < 1) throw new IllegalArgumentException("The batchSize must more than 0."); boolean isModel = element instanceof Model;
String[] columnArray = columns.split(","); for (int i = 0; i < columnArray.length; i++) columnArray[i] = columnArray[i].trim();
boolean isInTransaction = config.isInTransaction(); int counter = 0; int pointer = 0; int size = list.size(); int[] result = new int[size]; try (PreparedStatement pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { for (int i = 0; i < size; i++) { Map map = isModel ? CPI.getAttrs((Model) list.get(i)) : ((Record) list.get(i)).getColumns(); for (int j = 0; j < columnArray.length; j++) { Object value = map.get(columnArray[j]); if (value instanceof java.util.Date) { if (value instanceof java.sql.Date) { pst.setDate(j + 1, (java.sql.Date) value); } else if (value instanceof java.sql.Timestamp) { pst.setTimestamp(j + 1, (java.sql.Timestamp) value); } else { // Oracle、SqlServer 中的 TIMESTAMP、DATE 支持 new Date() 给值 java.util.Date d = (java.util.Date) value; pst.setTimestamp(j + 1, new java.sql.Timestamp(d.getTime())); } } else { pst.setObject(j + 1, value); } } pst.addBatch(); if (++counter >= batchSize) { counter = 0; int[] r = pst.executeBatch(); if (!isInTransaction) conn.commit(); //for (int j : r) { // result[pointer++] = j; //} ResultSet rs = pst.getGeneratedKeys(); while (rs.next()) { result[pointer++] = rs.getInt(1); } } } if (counter != 0) { int[] r = pst.executeBatch(); if (!isInTransaction) { conn.commit(); } //for (int i : r) { // result[pointer++] = i; //} ResultSet rs = pst.getGeneratedKeys(); while (rs.next()) { result[pointer++] = rs.getInt(1); } } return result; } }