java - JPA OneToOne,外键在 Spring Boot 上获取 null

标签 java hibernate spring-mvc spring-boot spring-data-jpa

我有@OneToOne JPA 关系。要保存的值来自 JSP 表单。我调试了我的代码:

id = 0
firstName = "john"
firstName = "doe"
security =
   id = 0
   username = "john1"
   password = "pwd"
   employee = null

这是我的实体:

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @NotBlank(message = "First Name is a required field.")
    private String firstName;
    @NotBlank(message = "Last Name is a required field.")
    private String lastName;
    @Valid
    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "employee", optional = false)
    private Security security;
...
}

@Entity
public class Security {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @NotBlank(message = "Username is a required field.")
    private String username;
    @NotBlank(message = "Password is a required field.")
    private String password;
    @OneToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "employee_id", nullable = false)
    private Employee employee;
...
}

我不明白为什么employee_id 变得为空:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'employee_id' cannot be null

我使用以下代码实现了 CommandLineRunner 并且它正在工作:

Employee employee = new Employee();
employee.setFirstName("Julez");
employee.setLastName("Jupiter");

Security security = new Security();
security.setUsername("julez");
security.setPassword("pwd");

employee.setSecurity(security);
security.setEmployee(employee);

employeeRepository.save(employee);

Spring Boot/MVC 或 Spring Data JPA 如何自动实现类似于我的 CommnadLineRunner 代码?我在这里搜索了很多教程和问题,但我只能找到使用 CommandLineRunner 而不是使用表单。谢谢。

最佳答案

保存员工,然后保存安全

Employee employee = new Employee();
employee.setFirstName("Julez");
employee.setLastName("Jupiter");

employee = employeeRepository.save(employee);

Security security = new Security();
security.setUsername("julez");
security.setPassword("pwd");

security.setEmployee(employee);
securityRepository.save(security);

关于java - JPA OneToOne,外键在 Spring Boot 上获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53277696/

相关文章:

java - Spring Security 未加载 js 和 css。 (给出404错误)

Spring Security自定义表单登录不适用于自定义loginProcessingUrl,返回404

java - 数据结构 : Checking if a record exists in a database?

java - 我如何在 Hibernate 中通过查询编写这个组?

java - 使用 slf4j 和 log4j 进行 Hibernate 日志记录不生成日志文件

java - 使用hibernate注释的Mysql异常

java - StreamingResponseBody 中的异常处理

java - 观察者模式无限循环

java - 无法解析主机 "<URL here>"没有与主机名关联的地址

java - 尝试获取jax-rs服务的WADL时报错500