bounty将在6天后过期。回答此问题可获得+50声望奖励。BugsOverflow希望引起更多人对此问题的关注:期待一个答案,显示我拥有的模型类应该是什么样子的,应该基于我描述的多对多关系
我有一个多对多的关系之间的树和节点:
- 树可以有许多节点。
- 节点可以位于多个树中。
在Tree表和Node表中也有复合主键。
所以我的模型类看起来像这样:
树:
@Entity
@Table(name = "tree")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class Tree {
@EmbeddedId
private TreeIdentifier treeIdentifier;
private LocalDateTime creationDate;
}
树标识符(这是树的主键):
@Embeddable
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class TreeIdentifier implements Serializable {
private String treeId;
private String siteId;
private Integer prodVersion;
@Override
public int hashCode() {
return Objects.hash(prodVersion, siteId, treeId);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TreeIdentifier other = (TreeIdentifier) obj;
return Objects.equals(prodVersion, other.prodVersion) && Objects.equals(siteId, other.siteId)
&& Objects.equals(treeId, other.treeId);
}
private static final long serialVersionUID = 1L;
}
节点:
@Entity
@Table(name = "node")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class Node {
@EmbeddedId
private NodeIdentifier nodeIdentifier;
private Long nodePosition;
}
节点标识符(节点的主键):
@Embeddable
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class NodeIdentifier implements Serializable {
private String nodeId;
private Integer nodeVersionId;
@Override
public int hashCode() {
return Objects.hash(nodeId, nodeVersionId);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NodeIdentifier other = (NodeIdentifier) obj;
return Objects.equals(nodeId, other.nodeId) && Objects.equals(nodeVersionId, other.nodeVersionId);
}
private static final long serialVersionUID = 1L;
}
现在,我正在努力弄清楚由于这个ManyToMany关系而激增的中间表在代码中应该是什么样子的:
树节点:
@Entity
@Table(name = "tree_node")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class TreeNode {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer treeNodeId;
private Tree tree;
private Node node;
}
我是按照Baeldung指南,到目前为止,我设法使它的工作与保存树和节点在数据库中,但现在的中间表不能弄清楚我应该如何注解字段正确(也应该如何注解树和节点类太?),你能帮助我吗?
我使用的指南:
1条答案
按热度按时间n3schb8v1#
您可以使用@MapsId;也许这就是你想要达到的目标。