当尝试使用JPA将多个对象插入MySQL时,尝试将Spring-boot从2.1.12版本更新到2.2.4时,DataIntegrityViolationException卡住了。
示例对象:
@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder(toBuilder = true)
@Table(name = "user")public class User {
@Id
@Column(name = "id")
@JsonProperty("id")
private String id;
@PrimaryKeyJoinColumn
@OneToOne(cascade = CascadeType.ALL)
@JsonProperty("status")
private UserStatus status;
}
和用户状态:
@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "user_status")
public class UserStatus {
@Id
@Column(name = "id")
@JsonProperty("id")
private String id;
public UserStatus(String userId) {
this.id = userId;
}
}
要向mysql插入对象,我使用默认的jpa存储库:
@Repository
public interface UserRepository extends JpaRepository<User, String> {
}
[使用spring-boot-2.1.x userRepository.save(user)
可以正常工作,但对于2.2.x会引发此异常:
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
此详细信息记录在日志中:
Cannot add or update a child row: a foreign key constraint fails (`test`.`user_status`, CONSTRAINT `user_status_ibfk_1` FOREIGN KEY (`id`) REFERENCES `user` (`id`) ON DELETE CASCADE)
[如果启用spring.jpa.show-SQL: true
,我发现使用spring-boot-2.2.x不会在User
实体上发生插入,但是在使用旧spring的情况下会发生插入。
我没有发现在连接到休眠状态的spring-boot中有任何重大变化,而且在进行相应更新后,休眠状态本身也没有任何重大变化。是否有发行说明中未描述的任何更新?
spring-boot 2.1.12使用Hibernate 5.3.15.Final,spring-boot 2.2.4使用Hibernate 5.4.10.Final
您的问题似乎与休眠问题HHH-13413 HHH-13171
原因是在5.4.0.CR1中引入的修复程序HHH-12436中,因此从那时起,当未提供@OneToOne(mappedBy =“”)时,一对一映射将不起作用。
[据我从JIRA的讨论中了解到,现在已经不是bug。有一个错误,他们像这样修复。我想对@PrimaryKeyJoinColumn
会有一些误解,因此人们不会正确使用它。
我想这会解决问题
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
@OneToOne(cascade = CascadeType.ALL)
@JsonProperty("status")
private UserStatus status;