我的足球比赛有以下层次结构。
@Entity
public class Match {
@Id
@GeneratedValue
protected Integer id;
@Column(name = "home_team_id")
private int homeTeamId;
@Column(name = "away_team_id")
private int awayTeamId;
private TeamScore homeScore;
private TeamScore awayScore;
}
@Entity(name = "team_score")
public class TeamScore {
@EmbeddedId
protected TeamScoreId id;
private List<Goal> goals;
}
@Embeddable
public class TeamScoreId {
@Column(name = "match_id")
private Integer matchId;
@Column(name = "team_id")
private int teamId;
}
我在将比赛中的 homeScore 和awayScore 与 TeamScore 实体映射时遇到问题。 第一个关心的是两个 @OneToOne 关系是否应该在这里。以及应该如何配置它们? 第二个与 TeamScoreId 中的 matchId 相关。如何执行此映射?
首先关心的是两个@OneToOne关系是否应该在这里。又该如何配置呢?
是的,我们应该为 TeamScore 进行一对一的配置。
第二个与TeamScoreId中的matchId有关。如何执行此映射? 该映射在没有注释的情况下以一对一的方式执行。
以 Java 代码保存的示例数据如下
session.persist(Match.builder()
.homeTeamId(1)
.awayTeamId(2)
.awayScore(TeamScore.builder()
.id(TeamScoreId.builder()
.matchId(1)
.teamId(1)
.build())
.goals(List.of(Goal.builder()
.score(1)
.build()))
.build())
.homeScore(TeamScore.builder()
.id(TeamScoreId.builder()
.matchId(2)
.teamId(2)
.build())
.goals(List.of(Goal.builder()
.score(2)
.build()))
.build())
.build());
我改变了如下的课程
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Match {
@Id
@GeneratedValue
protected Integer id;
@Column(name = "home_team_id")
private int homeTeamId;
@Column(name = "away_team_id")
private int awayTeamId;
@OneToOne(cascade = CascadeType.ALL)
private TeamScore homeScore;
@OneToOne(cascade = CascadeType.ALL)
private TeamScore awayScore;
}
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Goal implements Serializable {
@Id
@GeneratedValue
private Long id;
private int score;
@CreationTimestamp
Instant createDate;
}
@Entity(name = "team_score")
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TeamScore implements Serializable {
@EmbeddedId
protected TeamScoreId id;
@OneToMany(cascade = CascadeType.ALL)
private List<Goal> goals;
}
@Embeddable
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TeamScoreId implements Serializable {
@Column(name = "match_id")
private Integer matchId;
@Column(name = "team_id")
private int teamId;
}
在此处查找完整的工作示例。