【发布时间】:2018-06-01 21:06:07
【问题描述】:
我有一个应用程序可以教用户如何玩各种纸牌游戏。持久化的数据模型由一个TrainingSession 组成,它与Hands 具有单向一对多关系。
[EDIT] 澄清一下,Hand 在TrainingSession 的上下文之外不存在(即当TrainingSession 存在时它们被创建/销毁)。遵循数据驱动设计的原则,TrainingSession 被视为聚合根,因此使用单个 spring-data CrudRepository(即,没有为 Hand 创建存储库)
当我尝试使用 CrudRepository 保存 TrainingSession 时,我得到:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 无法添加或更新子行:外键约束失败 (blackjack.hand , 约束 FKrpuxac6b80xc7rc98vt1euc3n 外键 (id) 引用 training_session (tsid))
我的问题是通过 CrudRepository 实例的“save(trainingSession)”操作。我不明白为什么错误消息指出FOREIGN KEY (id) REFERENCES training_session (tsid))。这似乎是问题的原因,但我无法弄清楚为什么会这样或如何解决它。这种关系是单向的,Hand 类中没有任何内容涉及 TrainingSession。
代码,减去所有的 getter 和 setter,是:
@Entity
public class TrainingSession {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer tsid;
private String strategy;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="id")
private List<Hand> hands;
private int userId;
protected TrainingSession() {
}
public TrainingSession(int userId, Strategy strategy, List<Hand> hands) {
this.strategy = strategy.getClass().getSimpleName();
this.hands = hands;
this.userId = userId;
}
而Hand 是
@Entity // This tells Hibernate to make a table out of this class
public class Hand {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private int p1;
private String p1s;
private int p2;
private String p2s;
private int d1;
private String d1s;
private int trials;
private int score;
public Hand() {
}
【问题讨论】:
标签: spring hibernate jpa foreign-keys spring-data