技术:
- MySQL 8
- spring-boot-starter-parent 2.3.3.RELEASE
- 使用 spring-boot-starter-data-jpa
错误:
nested exception is org.springframework.dao.DataIntegrityViolationException: **could not execute statement; SQL [n/a]; constraint [null];**
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`emr`.`user_detail`, CONSTRAINT `user_detail_ibfk_1` FOREIGN KEY (`id`) REFERENCES `facility` (`id`))
DDL:
create table facility
(
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name varchar(60),
address varchar(200)
);
create table user_detail
(
id INTEGER PRIMARY KEY AUTO_INCREMENT,
username varchar(20) not null unique,
contactNo varchar(12),
facilityId int unsigned
foreign key (id) references facility(id)
);
Java 类:
@Entity
@Table(name= "user_detail")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String username;
@Column (name="contactNo")
private String contactNo;
@Column (name="facilityId")
private Integer facilityId;
//getter and setter
}
@Entity
@Table(name="facility")
public class Facility {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
}
假设 facility
表有 1 行 Id=1
和 name='Facility 1'
我正在尝试在 user_detail
表中为 facilityId=1
插入一行,但收到错误消息
据我所知,无法找到 facilityId
是 Facility.java
中的字段 id
并假设 null
user_detail.facilityId
列中不允许的值
我完全无法让代码理解 id
是外键字段。尝试了 @JoinColumn
的一些组合但没有成功。
最佳答案
异常表明,当您尝试保存 User 时,它将 null 保存为 facilityId。
要完成这项工作,您需要将设施指定为用户实体中的另一个表(您做错了)。
@Entity
@Table(name= "user_detail")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String username;
@Column (name="contactNo")
private String contactNo;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "facilityId", referencedColumnName = "id")
private Facility facility;
//getter and setter
}
根据您的要求,您需要指定关系。看来这里的关系应该是一对一的,所以我就这样标记了。
关于hibernate - 如何在spring boot data jpa中链接@Entity之间的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64634166/