【发布时间】:2020-02-12 12:43:31
【问题描述】:
我正在使用 JPA 存储库将简单的数据对象保存到数据库中。为了避免重复,我在多个字段上创建了唯一约束。如果现在应该保存根据唯一字段/约束的副本,我想捕获异常,记录对象,应用程序应该继续并保存下一个对象。但是在这里我总是得到这个异常:“org.hibernate.AssertionFailure: null id in de.test.PeopleDBO 条目(发生异常后不要刷新会话)”。
一般来说,我了解 hibernate 在做什么,但我如何才能恢复会话或启动新会话以继续保存下一个数据对象。请看下面的代码:
PeopleDBO.java
@Entity
@Data
@Table(
name = "PEOPLE",
uniqueConstraints = {@UniqueConstraint(columnNames = {"firstname", "lastname"}})
public class PeopleDBO {
public PeopleDBO(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
}
测试:
public void should_save_people_and_ignore_constraint_violation(){
final List<PeopleDBO> peopleList = Arrays.asList(
new PeopleDBO("Georg","Smith"),
new PeopleDBO("Georg","Smith"),
new PeopleDBO("Paul","Smith")
);
peopleList.forEach(p -> {
try {
peopleRepository.save(p);
} catch (DataIntegrityViolationException e) {
log.error("Could not save due to constraint violation: {}",p);
}
}
Assertions.assertThat(peopleRepository.count()).isEqualTo(2);
}
问题是,如果保存第二个人,就会违反唯一约束。错误日志发生,下一次调用 peopleRepository.save() 时抛出上述异常:
“org.hibernate.AssertionFailure: de.test.PeopleDBO 条目中的空 id(发生异常后不刷新 Session)”
我怎样才能避免这种行为?如何清理会话或开始新会话?
提前非常感谢 d.
------ 编辑/新想法------ 我刚刚尝试了一些事情,发现我可以实现一个 PeopleRepositoryImpl,如下所示:
@Service
public class PeopleRepositoryImpl {
final private PeopleRepository peopleRepository;
public PeopleRepositoryImpl(PeopleRepository peopleRepository) {
this.peopleRepository = peopleRepository;
}
@Transactional
public PeopleDBO save(PeopleDBO people){
return peopleRepository.save(people);
}
}
这在我的测试中运行良好。 ...你怎么看?
【问题讨论】:
标签: java hibernate jpa spring-data-jpa unique-constraint