org.springframework.dao.dataintegrityviolationexception在使用hibernate和spring引导数据jpa将spring引导从2.1.x更新到2.2.x之后

mbjcgjjk  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(374)

尝试将SpringBoot从2.1.12版更新到2.2.4版时,在尝试使用jpa将多个对象插入mysql时遇到了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是。
我没有发现连接到hibernate的spring boot有什么大的变化,在相应的更新之后hibernate本身也没有大的变化。是否有任何未在发行说明中描述的更新内容?

qlvxas9a

qlvxas9a1#

SpringBoot2.1.12使用Hibernate5.3.15.final,SpringBoot2.2.4使用Hibernate5.4.10.final
您的问题似乎类似于休眠问题hhh-13413hhh-13171
原因是在5.4.0.cr1中引入的补丁hhh-12436中,因此从那时起,当@onetoone(mappedby=“”)没有提供时,一对一Map就不起作用了。
我从吉拉的讨论中了解到,现在已经不是虫子了。有个窃听器,他们就这样把它修好了。我想我们之间有些误会 @PrimaryKeyJoinColumn 所以人们用得不对。
我想这会解决问题的

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
@JsonProperty("status")
private UserStatus status;

相关问题