Announcement Announcement Module
Collapse
No announcement yet.
Deleting existing data from table before running the JdbcBatchItemWriter with INSERTs Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Deleting existing data from table before running the JdbcBatchItemWriter with INSERTs

    I am struggling to create Job that is loading classifiers from flat file.

    I have configured FlatFileItemReader and JdbcBatchItemWriter to do the INSERTs and everything is fine up to the moment when I have to reload classifiers (run Job again with updated flat file).

    What I would like to do is to run "setup" step (DELETE FROM t1) before doing INSERT t1 values (a,b,c) again.

    How is this supposed to be done using Spring batch?

  • #2
    Add DELETE to your INSERT statement

    I'm assuming you have already defined an SQL statement for inserting the values (e.g. INSERT INSERT t1 values (a,b,c))

    Why not just add a DELETE or TRUNCATE statement to the beginning of the INSERT statement?

    Comment


    • #3
      Having DELETE prepended would not work because it would by executed for every chunk that I am getting from reader?

      I believe having of some kind of tasklet with customizable SQL statement that can be executed before or after loading of data might be good idea...

      I ended up by creating my own tasklet (postgresql specific) to do the job...

      Code:
      public class TablePrepareTasklet implements Tasklet, InitializingBean {
      
          private DataSource dataSource;
          private String table;
      
          @Override
          public RepeatStatus execute(StepContribution contribution,
                  ChunkContext chunkContext) throws Exception {
              dataSource.getConnection().createStatement().execute("DELETE FROM "+table);
              dataSource.getConnection().createStatement().execute("VACUUM "+table);
              return RepeatStatus.FINISHED;
          }
      
          public void setDataSource(DataSource dataSource) {
              this.dataSource = dataSource;
          }
      
          public DataSource getDataSource() {
              return dataSource;
          }
      
          public void setTable(String table) {
              this.table = table;
          }
      
          public String getTable() {
              return table;
          }
      
          @Override
          public void afterPropertiesSet() throws Exception {
              Assert.notNull(dataSource,"datasource must be set");
              Assert.notNull(table,"table name must be set");
          }
      }

      Comment

      Working...
      X