spring onetoone关系保存时未设置fk

svmlkihl  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(301)

这是我的密码:

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    private String password;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER, optional = false)
    private Employee employee;

    public User() {
    }

    //SETTERS AND GETER

}

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id")
    private User user;

    public Employee() {
    }

    //SETTERS AND GETER

}

为了我的服务,我试着这样做:

User user = new User();
    user.setUsername("my_username");
    user.setPassword("12345");

    Employee employee = new Employee();
    employee.setName("My Name");
    employee.setBirth(LocalDate.now());

    user.setEmployee(employee);

    userService.save(user);

应用程序上没有错误,也没有任何问题,但是在我的数据库中,user\u id列是空的,我该怎么做才能用user id自动设置user\u id?提前谢谢!

brjng4g3

brjng4g31#

正如hibernate文档中所述:
每当形成双向关联时,应用程序开发人员必须确保双方始终同步。
你用双向的 @OneToOne 因此,您应该同步关联的两侧:

User user = new User();
user.setUsername("my_username");
user.setPassword("12345");

Employee employee = new Employee();
employee.setName("My Name");
employee.setBirth(LocalDate.now());

// make both side  of bidirectional @OneToOne in-sync
user.setEmployee(employee);
employee.setUser(user);

userService.save(user);

相关问题