我有接下来的两个实体,它们之间有一个OneToOne关系:
@Entity
@Table(name = "tasks")
public class Task {
@OneToOne(mappedBy = "task", cascade = CascadeType.PERSIST)
private Tracker tracker;
/* More code */
}
@Entity
@Table(name = "trackers")
public class Tracker {
@OneToOne
@JoinColumn(name = "trk_task", unique = true)
private Task task;
/* More code */
}
我正在尝试运行此代码:
Task task = taskService.findDispatchableTask();
if (task != null) {
Tracker tracker = trackerService.findIdleTracker();
if (tracker != null) {
task.setTracker(tracker);
task.setStatus(TaskStatus.DISPATCHED);
taskService.save(task);
}
}
但我得到这个错误:
ERROR org.hibernate.AssertionFailure - an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)
org.hibernate.AssertionFailure: non-transient entity has a null id
我可以“解决”它将我的代码更改为:
Task task = taskService.findDispatchableTask();
if (task != null) {
Tracker tracker = trackerService.findIdleTracker();
if (tracker != null) {
tracker.setTask(task);
trackerService.save(tracker);
task.setTracker(tracker);
task.setStatus(TaskStatus.DISPATCHED);
taskService.save(task);
}
}
我的问题是,坚持OneToOne关系的正确方法是什么?在我的代码中,为什么我保存了关系的两个部分以使其工作?