死锁问题在使用Hibernate插入两个有依赖关系的实体时出现。

huangapple go评论70阅读模式
英文:

Deadlock while inserting two dependent entities using hibernate

问题

我有两个实体:用户(User)和动作(Action),通过ID将一个用户与多个动作关联。

我已经创建了它们的实例,并希望将它们插入到数据库中。

如果我先插入用户,然后再插入动作,那么一切都没问题。但如果我在插入用户之前插入动作,可能会出现死锁,因为动作在等待关联的用户被插入。

如何在插入动作实体之前检查用户是否已被插入?

代码示例:

@Entity
class User {
    @Id
    Integer userID;

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

    // 获取器和设置器
}

@Entity
class Action {
    @Id
    Integer actionID;

    @ManyToOne(fetch = FetchType.EAGER, targetEntity = User.class)
    @JoinColumn(name = "user_id", nullable = false)
    User user;

    // 获取器和设置器
}
英文:

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 = &quot;actions&quot;, targetEntity = Action.class, cascade = CascadeType.ALL)
    List&lt;Action&gt; actions = new ArrayList&lt;&gt;();

    //getters and setters
}


@Entity
class Action{
    @Id
    Integer actionID;

    @ManyToOne(fetch = FetchType.EAGER, targetEntity = User.class)
    @JoinColumn(name = &quot;user_id&quot;, nullable = false)
    User user;
    
    //getters and setters
}

答案1

得分: 2

在User中,mappedBy超过actions的部分应该是"user",它是Action类中引用User类的属性名称。但是,在设置中,我认为如果您在将新用户插入新用户之前将新操作添加到用户下的操作列表中,新操作将在同一语句中插入。(本来想将此作为评论添加,但声望不够。)

英文:

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.)

答案2

得分: 1

你应该从“owner”一侧进行保存。在这里,“owner”是你拥有外键的地方,因此在“Action”中。更多详情请查看此处

英文:

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

huangapple
  • 本文由 发表于 2020年10月19日 21:24:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64428303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定