hibernate - 如何在spring boot data jpa中链接@Entity之间的外键

标签 hibernate spring-data-jpa

技术:

  1. MySQL 8
  2. spring-boot-starter-parent 2.3.3.RELEASE
  3. 使用 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=1name='Facility 1' 我正在尝试在 user_detail 表中为 facilityId=1 插入一行,但收到​​错误消息

据我所知,无法找到 facilityIdFacility.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/

相关文章:

java - 如何在 JPA (Hibernate) 中映射 Class<?>

java - Spring Repository Rest Resource - 不保存子对象的问题

Spring Data JPA or spring hibernate 我需要学哪个RN

java - Spring Data JPA Lazy 加载注释为 Eager 的集合

java - Hibernate 包内的唯一性

java - Hibernate 从控制台记录异常

mysql - JPA 实体未保存在数据库中

spring-data-jpa - 找不到名称的参数绑定(bind)(Spring 数据 jpa)

java - 存储库找到 3 条记录,结果列表返回 6 条记录

java - 如何从实体类spring boot生成CRUD存储库类