備註:1、實體類需要實現 Serializable接口,並且將生成 serialVersionUID 放在第一行;
2、實體類中屬性的順序需和數據庫保持一致;
3、實體類中若需新增屬性必須在原先實體類屬性的末尾添加;
package com.dz;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @Description:JDBC批量插入反射操作數據庫
* @Date 2019年11月2日 下午1:49:46 @Author:DZ Copyright (c) 2019
*/
public class JdbcUtil2 {
public static final String DRIVER = "com.mysql.cj.jdbc.Driver"; // jdbc驅動
public static final String URL = "jdbc:mysql://localhost:3306/test?&useSSL=false&serverTimezone=UTC";
public static final String USER = "root";
public static final String PWD = "root";
public static final String BATCH_COUNT = "11";// 批量插入的數據量
/**
* @Description:進行數據庫的鏈接
* @return
* @Date 2019年11月2日 下午1:50:11 @Author:DZ
*/
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(DRIVER);// 加載驅動
conn = DriverManager.getConnection(URL, USER, PWD);// 創建鏈接
if (!conn.isClosed()) {
System.out.println("數據庫連接成功");
}
} catch (ClassNotFoundException e) {
System.out.println("數據庫驅動沒有安裝");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("數據庫連接失敗");
e.printStackTrace();
}
return conn;// 返回連接
}
/**
* @Description:關閉所有
* @param conn
* @param ps
* @param rs
* @Date 2019年11月2日 下午1:51:03 @Author:DZ
*/
public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs) {
try {
// 判斷是否被操作
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* @Description:關閉
* @param conn
* @param ps
* @Date 2019年11月2日 下午1:51:17 @Author:DZ
*/
public static void close(Connection conn, PreparedStatement ps) {
try {
// 判斷是否被操作
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* @Description:獲取表的所有列
* @param tableName
* @return
* @Date 2019年11月2日 下午1:51:40 @Author:DZ
*/
public static List<String> getColumns(String tableName) {
List<String> columnList = new ArrayList<String>();// 存放獲取到的列集合
Connection conn = JdbcUtil2.getConnection();// 獲取數據庫連接
PreparedStatement ps = null;
ResultSet rs = null;
ResultSetMetaData rsmd = null;
try {
ps = conn.prepareStatement("SELECT * FROM " + tableName);// 查詢數據庫邊表
rs = ps.executeQuery();
rsmd = rs.getMetaData(); // 獲取字段名
if (rsmd != null) {
int count = rsmd.getColumnCount();
for (int i = 1; i <= count; i++) {
columnList.add(rsmd.getColumnName(i));
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(conn, ps, rs);
}
return columnList;
}
/**
* @Description:獲取數據庫字段數量
* @param tableName
* @return
* @Date 2019年11月2日 下午2:02:45 @Author:DZ
*/
public static int getColumnCount(String tableName) {
Connection conn = JdbcUtil2.getConnection();// 獲取數據庫連接
PreparedStatement ps = null;
ResultSet rs = null;
ResultSetMetaData rsmd = null;
int count = 0;
try {
ps = conn.prepareStatement("SELECT * FROM " + tableName);// 查詢數據庫邊表
rs = ps.executeQuery();
rsmd = rs.getMetaData(); // 獲取字段名
if (rsmd != null) {
count = rsmd.getColumnCount();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(conn, ps, rs);
}
return count;
}
/**
* @Description:創建所需插入SQL
* @param TableName
* @return
* @Date 2019年11月2日 下午1:58:54 @Author:DZ
*/
public static String createSql(String TableName) {
int columnCount = getColumnCount(TableName);
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < columnCount; i++) {
buffer.append("?");
if (i < (columnCount - 1)) {
buffer.append(",");
}
}
String sql = "INSERT INTO " + TableName + " values (" + buffer + ")";
return sql;
}
/**
* @Description:反射執行批量插入
* @param <T>
* @param objects
* @param sql
* @Date 2019年11月2日 下午1:52:11 @Author:DZ
*/
public static <T> void saveBatch(List<T> objects, String tableName) {
long startTime = System.currentTimeMillis();
String sql = createSql(tableName);
Connection conn = JdbcUtil2.getConnection();
PreparedStatement ps = null;
int num = 0;// 數據插入的計數器
int count = 0;// 批量插入的批次數
try {
List<String> columns = getColumns(tableName);// 表中的字段
conn.setAutoCommit(false); // 設置手動提交
ps = conn.prepareStatement(sql);
for (int i = 0; i < objects.size(); i++) {
num++;
Object obj = objects.get(i);// 獲取List中的每一個對象
Class<?> c = obj.getClass();// 反射形成實際對象
Field[] fields = c.getDeclaredFields();// 通過反射獲取對象的屬性數組
for (int k = 0; k < columns.size(); k++) {
String dataSourceColumn = columns.get(k);
for (int j = 0; j < fields.length; j++) {
Field field = fields[j];// 拿到每一個屬性
field.setAccessible(true);// 設置些屬性是可以訪問的
String fieldName = field.getName();
if (fieldName.contentEquals(dataSourceColumn.replace("_", ""))) {// 數據庫表中的字段和實體類中的字段比較
String type = field.getType().toString();// 得到此屬性的類型
if (type.endsWith("String")) {
ps.setString(j, String.valueOf(field.get(obj)));
break;
} else if (type.endsWith("Date")) {
ps.setDate(j, new java.sql.Date(((Date) field.get(obj)).getTime()));
break;
} else {
try {
throw new Exception("反射異常!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
ps.addBatch();// 添加到批次
if (num > Integer.valueOf(BATCH_COUNT) - 1) {
count++;// 計算執行的批次數
ps.executeBatch();// 提交批處理
conn.commit();// 執行
ps.clearBatch();// 清除
System.out.println(num + " 條插入完成! ");
System.gc();// 提示釋放GC
num = 0;
}
}
ps.executeBatch();// 提交批處理
System.out.println("插入最後 " + (objects.size() - count * Integer.valueOf(BATCH_COUNT) + "條成功!"));
conn.commit();// 執行
ps.clearBatch();
long endTime = System.currentTimeMillis();
System.out.println("耗時:" + (endTime - startTime) / 1000 + "s");
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
close(conn, ps);// 關閉連接
}
}
/**
* @Description:獲取UUID
* @return
* @Date 2019年11月2日 下午2:52:12 @Author:DZ
*/
public static String getUUID() {
String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
return uuid;
}
/**
* @Description:創建測試所需實體對象
* @return
* @Date 2019年11月2日 下午3:16:38 @Author:DZ
*/
public static List<User> CreateVo() {
List<User> userList = new ArrayList<User>();
for (int i = 0; i < 100; i++) {
User user = new User(getUUID(), "xiaohua", "15", new Date());
userList.add(user);
}
return userList;
}
public static void main(String[] args) {
List<User> userList = CreateVo();
JdbcUtil2.saveBatch(userList, "user");
System.out.println("測試完成!");
}
}
實體類:
package com.dz;
import java.io.Serializable;
import java.util.Date;
/**
* @Description:用戶實體類
* @Date 2019年11月2日 下午3:23:18 @Author:DZ
* Copyright (c) 2019
*/
public class User implements Serializable {
private static final long serialVersionUID = -6297509897955271853L;
private String id;
private String name;
private String age;
private Date date;
private String version;
private String pageSize;
private String pageIndex;
public User(String id, String name, String age, Date date) {
this.id = id;
this.name = name;
this.age = age;
this.date = date;
}
public User(String name, String age, Date date) {
this.name = name;
this.age = age;
this.date = date;
}
public String getPageSize() {
return pageSize;
}
public void setPageSize(String pageSize) {
this.pageSize = pageSize;
}
public String getPageIndex() {
return pageIndex;
}
public void setPageIndex(String pageIndex) {
this.pageIndex = pageIndex;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
數據庫腳本:
Mysql建表腳本
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` varchar(11) DEFAULT NULL,
`date` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=301 DEFAULT CHARSET=utf8;