我有2个具有 OneToMany 所有权的表,并按如下所示创建了实体
表1- 网络具有主键作为networkId
表2- NetworkAttributes 以FK作为networkId,但是应结合使用“ networkId ”和“ 名称”将记录视为唯一列[网络表中不存在属性表中的名称列],这里我存储了多个网络参数的默认值,并且可以按照以下<表中的表结构,在不同的网络下重复这些参数NetworkAttributes ”,
表结构:-
网络表:
networkID | networkName | networkType
H123M nrouter X
N123Y testR J
NetworkAttributes表:[默认值存储的键值类型]
networkID | name | value
H123M maxIpUser 10
H123M maxRouterUser 15
N123Y maxIpUser 23
N123Y maxRouterUser 25
网络实体:-
@Entity
@Table(name = "NETWORK")
public class Network implements Serializable {
private static final long serialVersionUID = 1L;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id", nullable = false)
private Customer customer;
@Id
@NotNull
@Column (name = "NETWORKID")
private String networkId;
@Column (name = "networkName")
private String networkName;
@Column (name = "networkType")
private String networkType;
@Column (name = "onlyActive")
private boolean onlyActive;
@OneToMany (fetch = FetchType.LAZY, mappedBy = "network")
private List<NetworkAttributes> networkAttributes;
// Setter / Getter
网络属性实体:-
@Entity
@Table (name = "NETWORK_ATTRIBUTES")
public class NetworkAttributes implements Serializable {
private static final long serialVersionUID = 1L;
@Column (name = "name")
private String name;
@Column (name = "value")
private String value;
@ManyToOne (fetch = FetchType.LAZY)
@JoinColumn (name = "network_Id")
private Network network;
// setter / getter
问题: 使用这种表结构,我无法在 Network Attributes 表中为同一网络插入不同的参数。给出唯一的约束错误。有任何建议吗
例如,您可以看到我正在尝试在下面的记录中插入,但是由于networkId为FK,因此不允许插入第二和第四记录。
H123M maxIpUser 10
H123M maxRouterUser 15
N123Y maxIpUser 23
N123Y maxRouterUser 25
答案 0 :(得分:0)
这是一个“派生身份”,因此NetworkAttributes
可以与@EmbeddedId
进行映射,如下所示:
@Embeddable
public class NetworkAttributesId {
String name;
String networkId; // corresponds to PK type of Network
}
@Entity
@Table (name = "NETWORK_ATTRIBUTES")
public class NetworkAttributes implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
NetworkAttributesId id;
@ManyToOne (fetch = FetchType.LAZY)
@JoinColumn (name = "network_Id")
@MapsId("networkId") // maps networkId attribute of embedded id
private Network network;
@Column (name = "value")
private String value;
...
}
在JPA 2.2 spec的第2.4.1节中讨论了派生的身份(带有示例)。