Spring batch ItemWriter Insert into two related table fail

  Kiến thức lập trình

Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table “table2 violates foreign key constraint “tab1_tab2_FK”


I’m trying to insert into an ItemWriter in two related tables.

Table1 and table2, table 2 contains a foreing key from table 1.

in the write function of my writer I execute two jdbcTeplate. update (one to insert into table 1 and the second for table 2)

I have chunk = 100.

I have a constraint violation exception because foreing keys are persisted before their parents.

Here is the Write function of my writer:

public void write(List<? extends ProcessorOutput> items) throws Exception {

    List<ProcessorOutput> itemList = (List<ProcessorOutput>) items;

    List<MyTab1Dto> itemsTab1 = itemList.stream().map(item -> item.getMyTab1Dto()).collect(Collectors.toList());

    int[] tab1InsertReturn = jdbcTemplate.
            batchUpdate(requestTab1Insert, new Tab1BatchInsertPreparedStatementSetter(itemsTab1));

    List<MyTab2Dto> itemsTab2 = itemList.stream().map(item -> item.getMyTab2Dto()).collect(Collectors.toList());

    int[] tab2InsertReturn = jdbcTemplate.
            batchUpdate(requestTab2Insert, new Tab2BatchInsertPreparedStatementSetter(itemsTab2));


New contributor

Hamzaz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.