JPA OneToOne,外键在Spring Boot上为空

时间:2018-11-13 09:25:10

标签: 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代码?我在SO中搜索了很多教程和问题,但是我只能使用CommandLineRunner而不是使用表格。谢谢。

2 个答案:

答案 0 :(得分:0)

保存Employee,然后保存Security

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);

答案 1 :(得分:0)

  

确保设置对象的OneToOne的值,如果OneToOne是双向OneToOne关系的一部分,请确保在两个对象中都设置OneToOne,JPA不会为您维护双向关系。

wikibooks

例如您可以定义同时设置双方的领导实体:

@Entity
public class Security {
    public void setEmployee(Employee employee) {
        this.employee = employee;
        this.employee.setSecurity(this);    
    }
}
相关问题