【发布时间】:2019-04-16 02:10:57
【问题描述】:
我有@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 代码?我在 SO 中搜索了很多教程和问题,但我只能找到使用 CommandLineRunner 而不是使用表单。谢谢。
【问题讨论】:
-
您的
Employee实体为空而不能为空?还是我错过了什么? -
@Pijotrek 安全实体上的员工属性为空。也许这就是 fk employee_id 为空并导致错误的原因。如果您可以在我的 CommandLineRunner 中注意到,我通过 setEmployee 方法手动设置了员工的值并工作。
-
我认为 Spring Boot 神奇地做到了这一点,因为在受控对象中,员工对象立即传递给 employeeRepository.save() 方法,而无需手动设置。这就是大多数示例的完成方式。
标签: java hibernate spring-mvc spring-boot spring-data-jpa