0

I have two entities: User and Action related One user to many Actions by ID.

I created instances of them and want to insert them to DB.

It's okay if I insert the User first and then the Action. But if I insert Action before insert User i will get deadlock because Action waiting for realted User will be inserted.

How to check if User was inserted before insert Action entity?

Code example:

@Entity
class User{
    @Id
    Integer userID;

    @OneToMany(mappedBy = "actions", targetEntity = Action.class, cascade = CascadeType.ALL)
    List<Action> actions = new ArrayList<>();

    //getters and setters
}


@Entity
class Action{
    @Id
    Integer actionID;

    @ManyToOne(fetch = FetchType.EAGER, targetEntity = User.class)
    @JoinColumn(name = "user_id", nullable = false)
    User user;
    
    //getters and setters
}
Byoliee
  • 29
  • 4
  • you should not have any save method to db for action. You should just have a save method for user , since saving only action is not necessary and wrong. – fatma zehra güç Oct 19 '20 at 13:41

2 Answers2

2

In User, mappedBy over actions is supposed to be "user", the name of the property in the Action class that refers to the User class. But then, in the setup, I believe if you add the new Action to the List of Actions under a User before you insert the new User, the new Action will be inserted in the same statement. (Was going to add this as a comment but not enough rep.)

workaholic
  • 74
  • 7
1

You should save being from the owner side. The owner is where you have your foreign key, hence in Action. check here for more

Aman
  • 1,627
  • 13
  • 19