adminId不在一对一关系springboot中保存在用户表中

时间:2016-07-26 09:57:17

标签: mysql spring hibernate spring-boot

我已经映射了用户和管理员之间的一对多关系,如用户类

所示
@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "userId")
    private Long id;
    @Column(nullable = false)
    private String name;
    @Column(unique = true, nullable = false)
    private String email;
    @Column(nullable = false)
    private long timestamp;

    @OneToOne
    @JoinColumn(name = "adminId")
    Admin admin;

现在我试图通过使用hibernate的SessionFactory将值1插入users表中的adminId字段来保存用户,如图所示

public void save(User user) {

        //User userAdmin = new User();
        long id = 1 ;
        user.setId(id);

        getSession().save(user);
    }

EDITTED

考虑到getter和setter,这些是admin表中的字段

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "adminId")
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = true)
    private String department;

我的挑战是,当我保存时,在用户表中引用管理外键的adminId字段上没有插入(值为1)

请帮助!

1 个答案:

答案 0 :(得分:0)

您必须首先获取ID为1的Admin实体,然后将其设置为新用户:

    @Transactional
    public void save(User user) {
        Admin admin = getSession.createQuery("from Admin a where a.id = ?)
                                .setParameter(0, 1);
        user.setAdmin(admin);
        getSession().save(user);
    }