JPA根据另一个密钥自动生成复合密钥

时间:2018-08-21 15:05:33

标签: java hibernate jpa hibernate-mapping

地址表具有复合键的以下结构,user_id是外键,也是复合PK的一部分:

address_ordinal(PK)     user_id(PK, FK)
     1                     1
     2                     1
     1                     2
     2                     2
     3                     2
     1                     3

地址类别:

@Entity
public class Address implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private AddressPK id;
}

@Embeddable
public class AddressPK implements Serializable {

    @GeneratedValue  //what strategy ?
    @Column(name="address_ordinal")
    private Integer addressOrdinal; // is there any strategy or any other way to auto generate addressOrdinal based on user_id ?

    @Column(name="user_id")
    private Integer userId;
    //equals() and hashCode()
}

@Entity
@Table(name = "user_detail")
public class UserDetail implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long userId;
    //setters and getters
}

在JPA中,是否可以基于另一个字段自动生成复合密钥的一个字段?请参阅上面的示例数据,了解如何生成。基本上,它是用户及其多个地址的简单映射。
还是我必须在地址表中手动更新组合键?

0 个答案:

没有答案