private static final int MaxBatchLength = 100;
public void updateBatch(List<T>list, BaseMapper<T> mapper){
if (!Proxy.isProxyClass(mapper.getClass())){
throw new RuntimeException("mapper必須是代理對象");
}
InvocationHandler invocationHandler = Proxy.getInvocationHandler(mapper);
if (null==invocationHandler){
throw new RuntimeException("mapper必須是有處理器的代理對象");
}
Field fieldSession;
try {
fieldSession = invocationHandler.getClass().getDeclaredField("sqlSession");
} catch (NoSuchFieldException e) {
throw new RuntimeException("從mapper代理對象中獲取不到sqlSession", e);
}
Field fieldMapper;
try {
fieldMapper = invocationHandler.getClass().getDeclaredField("mapperInterface");
} catch (NoSuchFieldException | SecurityException e) {
throw new RuntimeException("從mapper代理對象中獲取不到mapperInterface", e);
}
fieldSession.setAccessible(true);
SqlSession session;
try {
session = (SqlSession) fieldSession.get(invocationHandler);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException("從mapper代理對象中獲取sqlSession失敗,不應該出現此異常", e);
}
fieldMapper.setAccessible(true);
Class<?> mapperInterface;
try {
mapperInterface = (Class<?>) fieldMapper.get(invocationHandler);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException("從mapper代理對象中獲取mapperInterface失敗,不應該出現此異常", e);
}
// 方法名(mybatis的對應xml中的sql語句的id)
String methodName = mapperInterface.getName() + ".updateEntityBatch";
System.out.println("獲取方法的SQL:"+methodName);
//傳遞參數保證,要更新的字段存在(若沒有判空,則可以不用傳遞參數)
BoundSql boundSql = session.getConfiguration().getMappedStatement(methodName).getBoundSql(list.get(0));
//是否是獨立的事務
boolean atmo = true, succ = false;
System.out.println("每次批量執行最大長度為:"+MaxBatchLength );
//獲取批量執行的sql
String sql = boundSql.getSql();
//獲取連接
Connection connection = null;
PreparedStatement ps = null;
List<Closeable> closeables = new LinkedList<>();
try {
connection = session.getConnection();
if (atmo = null == connection || connection.isClosed()) {
DataSource dataSource = session.getConfiguration().getEnvironment().getDataSource();
connection = dataSource.getConnection();
//事務不自動提交
connection.setAutoCommit(false);
System.out.println("session中的連接不可使用,使用獨立的連接和事務");
} else {
System.out.println("使用session的連接,事務和session保持一致");
}
ps = connection.prepareStatement(sql);
int index = 0;
System.out.println("需要批量更新"+list.size()+"個對象");
for (int i = 0, j = list.size(); i < j; i++, index++) {
T t = list.get(i);
//將實體類轉換為map
BeanMap map = BeanMap.create(t);
System.out.println("綁定對象:"+ map);
for (int ii = 1, jj = boundSql.getParameterMappings().size(); ii <= jj; ii++) {
ParameterMapping parameterMapping = boundSql.getParameterMappings().get(ii - 1);
String name = parameterMapping.getProperty();
Object value = map.get(name);
if (null == value) {
// 為空時候嘗試取默認值
value = map.get(name + "Default");
}
if (null != value && value instanceof Date) {
Timestamp date = new Timestamp(((Date) value).getTime());
value = date;
}
// 單獨處理clob類型
if (JdbcType.CLOB.equals(parameterMapping.getJdbcType())) {
StringReader sr = new StringReader(null == value ? "" : value.toString());
ps.setClob(ii, sr);
closeables.add(sr);
} else {
ps.setObject(ii, value, parameterMapping.getJdbcType().TYPE_CODE);
}
}
ps.addBatch();
if (index > MaxBatchLength) {
ps.executeBatch();
ps.clearBatch();
index = 0;
}
}
if (index > 0) {
//執行剩下的
ps.executeBatch();
}
succ = true;
}catch (Exception e){
throw new RuntimeException("批量更新失敗",e);
}finally {
// 如果是獨立的事務
if (atmo && null != connection) {
log.info("檢測到獨立事務,判斷提交/回滾");
if (succ) {
try {
connection.commit();
log.info("獨立事務提交成功");
} catch (SQLException e) {
log.info("獨立事務提交失敗");
throw new RuntimeException(e);
}
} else {
try {
connection.rollback();
log.info("獨立事務回滾成功");
} catch (SQLException e) {
log.info("獨立事務回滾失敗");
throw new RuntimeException(e);
}
}
}
if (null != ps) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (atmo && null != connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
for (Closeable closeable : closeables) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}