我有以下带有约束的实体:
// Associated entry
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"userId", "associationDate"}))
public class Association extends coreEntity {
@Column(nullable = false)
private Long userId;
@Column(nullable = false)
private LocalDate associationDate;
@Column(nullable = false)
private LocalTime start;
@Column(nullable = false)
private LocalTime end;
private Duration breakTime;
@Column(nullable = false)
@OneToMany(fetch = FetchType.EAGER)
private Set<ProjectEntry> projects;
// getter setter
}
// the entry that causes the Problems with unique constraints
@Data
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"projectId", "userId", "date"}))
public class ProjectEntry extends CoreEntity {
@Column(nullable = false)
private Long projectId;
@Column(nullable = false)
private Long userId;
@Column(nullable = false)
private Duration duration;
@Column(nullable = false)
private LocalDate anyDate;
//getter setter
}
服务实现方法
@Override
@Transactional
public Association create(Association association ) {
checkNotNull(association);
association.setId(null);
association.getProjects().forEach(projectEntry -> {
checkObjectNotNull(projectEntry );
projectEntryRepo.save(projectEntry);
});
// Here is the problem
}
return associationRepo.save(association);
当违反约束时,将会抛出异常。 但是,如果 List 的第一个对象有效,而第二个对象违反了 Unique 约束,则第一个 Entry-create 仍将被提交。但如果有人错了,就不应该犯任何错误。所有请求都应该回滚。 我应该如何注释该方法或处理这个问题?
最佳答案
@Transactional(rollbackFor = {Exception_NAME.class,...})
public Association create(Association association ) {...}
关于java - 如果列表发生唯一约束错误,Spring 不会回滚。如何启用整个列表的回滚?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61205811/