我在使用Schedule
关系保存ScheduleItems
实体时失败了。
我希望以下工作:
Schedule
实体。Schedule
传递给ScheduleService.save
方法,该方法在数据库中插入/更新Schedule
和相关的ScheduleItem
。我的实体类如下所示:
@Entity
public class Schedule {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "SCHEDULE_DATE")
private LocalDate date;
@ManyToOne
@JoinColumn(name = "SHOP_ID")
private Shop shop;
@Version
private int version;
@JsonManagedReference
@OneToMany(mappedBy = "schedule", orphanRemoval = true, cascade = {}, fetch = FetchType.EAGER)
private Set<ScheduleItem> items = new HashSet<>();
.....
}
@Entity
@IdClass(ScheduleItemId.class)
public class ScheduleItem {
@JsonBackReference
@Id
@ManyToOne
@JoinColumn(name = "SCHEDULE_ID")
private Schedule schedule;
@Id
@ManyToOne
@JoinColumn(name = "EMPLOYEE_ID")
private Employee employee;
private int startTime;
private int duration;
@Enumerated(EnumType.STRING)
@Column(name = "WORK_TYPE")
private WorkType type;
......
}
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@JsonBackReference
@ManyToOne
private Shop shop;
@ManyToOne
private Position position;
private boolean active = true;
@Enumerated(EnumType.STRING)
private EmploymentType employment;
......
}
我已经阅读了很多相关主题和StackOverflow问题,我仍然有一些问题:
save
方法中传递的实体已分离。为了保存它,我必须PERSIST它(如果有新的Schedule
)或MERGE(如果存在Schedule
)?Schedule
- &gt;然后迭代ScheduleItem
并设置Schedule
和Employee
关系 - &gt;然后我坚持/合并ScheduleItem
s?我的服务保存方法如下:
@Transactional
public Schedule saveOrUpdate(Schedule schedule) {
final Schedule managedSchedule = em.merge(schedule); <----ERROR
List<ScheduleItem> managedItems = schedule.getItems().stream()
.map(item -> {
item.setSchedule(managedSchedule);
item.setEmployee(em.find(Employee.class, item.getEmployee().getId()));
return em.merge(item);
})
.collect(Collectors.toList());
managedSchedule.setItems(managedItems);
return managedSchedule;
}
当我尝试保存计划时,我将分离的实体传递给persist:com.xxx.employee.Employee; 。但为什么?我没有在任何实体中设置级联属性。
如果我在cascade=ALL
的{{1}}上设置Set<ScheduleItems> items
,我会收到同样的错误。
触发Schedule
方法的测试方法:
ScheduleService.saveOrUpdate
有人可以帮助我吗?
提前致谢。