Spring Transaction with dependent insertions not working

219 Views Asked by At

Here's my code:

Entities:

@Entity
public class A {
    @Id
    Long aId;
    ...
}

@Entity
public class B {
    @Id
    Long bId;
    Long aId;
    ...
}

Service:

@Transactional
public void multiInsert() {
    A a = createA();
    aRepository.save(a);

    B b = createBFromA();
    bRepository.save(b);
}

When I am try to do bRepository.save(), it is failing with the following error:

Caused by: java.sql.SQLException: Cannot add or update a child row: a foreign key constraint fails (b, CONSTRAINT a_to_b FOREIGN KEY (aId) REFERENCES a (aId))

My guess is a is not persisted before we are trying to save b due to which the foreign key constraint is failing.

I am aware that for foreign key, I should use @JoinColumns. But is there a way to make it work without that.

0

There are 0 best solutions below