我正在尝试构建一个简单的全栈井字游戏应用程序,但在定义一对多关系时遇到一些问题。
这里的上下文,我们有一个主桌面游戏:
CREATE TABLE `tictactoe`.`games` (
`idgames` INT NOT NULL AUTO_INCREMENT,
`gridConf` VARCHAR(45) NOT NULL,
`playerNum` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idgames`));
还有一个辅助表,游戏步骤:
CREATE TABLE `tictactoe`.`gamesteps1` (
`idgamesteps` INT NOT NULL AUTO_INCREMENT,
`idgame` INT NOT NULL,
`step` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idgamesteps`));
我想定义一个(游戏)与许多(游戏步骤)的关系, 其中 Gamesteps.idgamesteps 和 Gamesteps.games 组合是 Gamesteps 表上的主键。
我有两个疑问:
1-我应该如何定义我的数据库表?我有查询权限还是需要一个显式的外键?
2-JPA注释: 这是我的实体:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Games {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idgames;
private String gridConf;
private Integer playerNum;
@OneToMany(mappedBy = "idgames")
private Set<GameSteps> gameSteps;
//all setter/getters
辅助表:
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class GameSteps {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idGameSteps;
@ManyToOne
@JoinColumn(name = "idgames", referencedColumnName = "idgames")
private Integer idgame;
private String step;
//all setter/getter
我正在尝试归档的是可以通过主实体(游戏)上的 CRUDRepository 界面执行 Save/findAll 操作,并在所有其他子实体(游戏步骤)上执行自动 Save/findAll 操作。
对我来说,不清楚应该在哪里使用 @OneToMany
或 @ManyToOne
注释。
目前我只遇到异常(exception)情况。
如果需要其他信息,只需询问,任何类型的帮助/文档都会非常感激!
谢谢!
<小时/>根据 @Smutje 评论,我已更改为:
public class GameSteps {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idGameSteps;
@ManyToOne
@JoinColumn(name = "idgames", referencedColumnName = "idgames")
private **Games** idgame;
和
@OneToMany(mappedBy = "**idgame**")
private Set<GameSteps> gameSteps;
但得到:
java.sql.SQLSyntaxErrorException: Unknown column 'idgames' in 'field list'
最佳答案
如果您希望 Gamesteps.idgamesteps 和 Gamesteps.games 成为 Gamesteps 表上的主键。您必须使用标签@EmbeddedId和@Embeddable,您的复合键必须是另一个类。
The primary key fields are defined in an embeddable class. The entity contains a single primary key field that is annotated with @EmbeddedId and contains an instance of that embeddable class.
类似这样的事情
import javax.persistence.*;
@Entity
public class GameSteps {
@EmbeddedId
private GameStepsPK pk;
private String step;
// getters and setters
GameStepsPK 将是复合键
import java.io.Serializable;
import javax.persistence.*;
@Embeddable
public class ExploitationEvaluationPK implements Serializable {
private static final long serialVersionUID = 1L;
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idGameSteps;
@ManyToOne
@JoinColumn(name = "idgames", referencedColumnName = "idgames")
private Games idgames;
您还可以阅读此内容 here
希望这有帮助
关于java - Spring Boot JPA - 定义一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59840815/