OneToOne between two tables with shared primary key

前端 未结 4 1003
[愿得一人]
[愿得一人] 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:43

    If you use Hibernate you can also use

    public class Validation {
    
        private Long validationId;
        private User user;
    
        @Id
        @GeneratedValue(generator="SharedPrimaryKeyGenerator")
        @GenericGenerator(name="SharedPrimaryKeyGenerator",strategy="foreign",parameters =  @Parameter(name="property", value="user"))
        @Column(name = "VALIDATION_ID", unique = true, nullable = false)
        public Long getValidationId(){
            return validationId;
        }
    
        @OneToOne
        @PrimaryKeyJoinColumn
        public User getUser() {
            return user;
        }
    
    }
    

    Hibernate will make sure that the ID of Validation will be the same as the ID of the User entity set.

提交回复
热议问题