英文:
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 = "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
}
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论