1717
1818public class SqlServerBulkInsert <TEntity > implements ISqlServerBulkInsert <TEntity > {
1919
20+ private List <IColumnDefinition <TEntity >> columnMappings ;
21+
2022 private final AbstractMapping <TEntity > mapping ;
2123
24+
2225 public SqlServerBulkInsert (AbstractMapping <TEntity > mapping )
2326 {
2427 this .mapping = mapping ;
@@ -30,7 +33,7 @@ public void saveAll(Connection connection, Stream<TEntity> entities) {
3033
3134 public void saveAll (Connection connection , SQLServerBulkCopyOptions options , Stream <TEntity > entities ) {
3235
33- SchemaUtils . validateColumnMapping (connection , mapping );
36+ validateAndInitializeWithMetaData (connection );
3437
3538 // Create a new SQLServerBulkCopy Instance on the given Connection:
3639 try (SQLServerBulkCopy sqlServerBulkCopy = new SQLServerBulkCopy (connection )) {
@@ -39,7 +42,7 @@ public void saveAll(Connection connection, SQLServerBulkCopyOptions options, Str
3942 // The Destination Table to write to:
4043 sqlServerBulkCopy .setDestinationTableName (mapping .getTableDefinition ().GetFullQualifiedTableName ());
4144 // Resort
42- List <IColumnDefinition <TEntity >> columnMappings = SchemaUtils . getSortedColumnMappings ( connection , mapping ) ;
45+ List <IColumnDefinition <TEntity >> columnMappings = this . columnMappings ;
4346 // The SQL Records to insert:
4447 ISQLServerBulkData record = new SqlServerBulkData <TEntity >(columnMappings , entities .iterator ());
4548 // Finally start the Bulk Copy Process:
@@ -58,4 +61,14 @@ public void saveAll(Connection connection, Collection<TEntity> entities) throws
5861
5962 saveAll (connection , entities .stream ());
6063 }
64+
65+ private synchronized void validateAndInitializeWithMetaData (Connection connection ) {
66+ if (columnMappings == null ) {
67+ // Make sure the mapping is valid:
68+ SchemaUtils .validateColumnMapping (connection , mapping );
69+
70+ // Now set this Bulk Inserters mappings:
71+ this .columnMappings = SchemaUtils .getSortedColumnMappings (connection , mapping );
72+ }
73+ }
6174}
0 commit comments