我目前有2个类:AgencyDetail和AgencyBlockedDayDetail定义如下:
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "startDate","endDate","agency_detail"}))
public class AgencyBlockedDayDetail extends CalendarEvent {
@ManyToOne(optional=false)
@JoinColumn(name = "agency_detail", nullable=false)
private AgencyDetail agencyDetail;
请注意,变量startDate和endDate在超类CalendarEvent中声明。
AgencyDetail类是:
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name"}))
@RooJpaActiveRecord(finders = { "findAgencyDetailsByNameEquals"})
public class AgencyDetail extends LocationDetail {
@NotNull
private String name;
@OneToMany(mappedBy = "agencyDetail", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<AgencyBlockedDayDetail> blockedDays;
问题是我有两个AgencyBlockedDayDetail对象,即
bdd1引用了AgencyDetail对象agency01和
bdd2,引用了AgencyDetail对象agency02。
我的情况是我在bdd2上更新AgencyDetail,如下所示:
bdd2.setAgencyDetail(agency01);
agencyBlockedDayDetailService.updateAgencyBlockedDayDetail(bdd2);
此时,根据我的equals()和hashCode()方法,bdd1和bdd2在逻辑上是等价的。但是,在服务层的update方法中运行merge()之后,bdd2将被完全删除/删除。我宁愿抛出约束违例异常,因为试图保存它会违反我指定的唯一约束(即startDate,endDate,agencyDetail)。
这是正确的行为吗?我可以让它抛出约束违规异常而不仅仅是合并吗?这可能更好,因为用户可能意外地输入了错误的日期或代理商详细信息。
我失败的jUnit测试示例如下:
public void test() {
//now attempt to update agency
AgencyDetail agency = agencyDetailService.findAgencyDetail(3l);//Get agency Rolling Hills
AgencyBlockedDayDetail agencyBdd= AgencyBlockedDayDetail.findAgencyBlockedDayDetailsByAgencyDetail(agency).getSingleResult();
assertTrue(agencyBdd.getDescription().equalsIgnoreCase("Blocked Day for Rolling Hills"));
AgencyDetail agency02 = agencyDetailService.findAgencyDetail(2l);//Get agency Fairlane Agencies
agencyBdd.setAgencyDetail(agency02);
agencyBlockedDayDetailService.updateAgencyBlockedDayDetail(agencyBdd);
agency02 = agencyDetailService.findAgencyDetail(2l);//Get agency Fairlane Agencies
}