While there is an accepted answer already, its less likely that we get input data in files and in the required format. In such cases the below code ( java 21 ) may help
private int bulkInsertToTable(List<Games> entities, String tableName, Connection conn) throws Exception {
PgConnection pgConn = conn.unwrap(PgConnection.class);
CopyManager copyManager = new CopyManager(pgConn);
String copySql = String.format(
"COPY %s (column_name_1, c2, c3, c4, c5 ) FROM STDIN WITH DELIMITER '|'",
fullTableName
);
CopyIn copyIn = copyManager.copyIn(copySql);
// actual COPY operation happens here
for (Games entity : entities) {
byte[] bytes = entity.toRow().getBytes(StandardCharsets.UTF_8);
copyIn.writeToCopy(bytes, 0, bytes.length);
}
long rowsInserted = copyIn.endCopy();
conn.commit();
long duration = System.currentTimeMillis() - start;
log.info("Bulk inserted {} records into {} in {} ms", rowsInserted, fullTableName, duration);
return (int) rowsInserted;
}
public String toRow() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
return String.join("|",
String.valueOf(column_name_1),
String.valueOf(c2),
dateFormat.format(c3),
String.valueOf(c4),
c5 + "\n");
}