OneToOne between two tables with shared primary key

前端 未结 4 1000
[愿得一人]
[愿得一人] 2020-12-09 05:33

I\'m trying to set up the following tables using JPA/Hibernate:

User:

userid - PK
name 

Validation:

userid - PK, FK(user)
code

There may

4条回答
  •  暖寄归人
    2020-12-09 05:41

    You need to set both userId and user.

    If you set just the user, then the id for Validation is 0 and is deemed detached. If you set just the userId, then you need to make the user property nullable, which doesn't make sense here.

    To be safe, you can probably set them both in one method call:

    @Transient
    public void setUserAndId(User user){
        this.userId = user.getId();
        this.user = user;
    }
    

    I marked the method @Transient so that Hibernate will ignore it. Also, so you can still have setUser and setUserId work as expected with out any "side effects."

提交回复
热议问题