我有一个名为“Attributes”的表,它有 3 个可以为空的字段的 PK。在这种情况下,Style_no 不为空,但 item_no 和 size_no 为空。
是否可以有一个字段可以为空的 Embeddeble PK?
@Entity
@Table(name="ATTRIBUTE")
public class Attribute {
@EmbeddedId
private AttributePK attrPK;
...
@Embeddable
public static class AttributePK implements Serializable{
private static final long serialVersionUID = -2976341677484364274L;
@Column(name="STYLE_NO", nullable=true)
protected String styleNo;
@Column(name="ITEM_NO", nullable=true)
protected String itemNo;
@Column(name="SIZE_NO", nullable=true)
protected String sizeNo;
...
当我尝试引用一个字段时,例如style_no 结果数量为0。
@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="attrPK.styleNo")
@MapKey(name="attrPK.name")
public Map<String,Attribute> attributesX;
或
@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="STYLE_NO", referencedColumnName="STYLE_NO")
private List<Attribute> attributes;
当我删除 item_no 和 size_no 作为 pk 时,我收到了一个有效结果。
编辑: 让我的问题更具体。根据 JPA 指南或“常识”是否不允许对 EmbeddebedId 使用可为空的字段?如果不是,我需要添加什么注释或逻辑才能使其在不添加另一个 PK 的情况下工作? 一旦用值填充 PK 中的可为空字段。结果正确。
非常感谢!
最佳答案
自 you must not use null in your PK ,这是你应该做的:
- 添加 surrogate primary key .
您仍然可以使用部分索引(在 PostgreSQL 中)实现唯一性约束和默认 PK 索引:
在 my_table (Style_no, item_no, size_no) WHERE (item_no IS NOT NULL AND size_no IS NOT NULL) 上创建唯一索引 style_item_size_idx;
关于java - JPA 可嵌入 PK 和可为空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23825060/