[英]Using a Spring Entity inside another Spring Entity
當我嘗試向“用戶”類中指定的ArrayList中添加“游戲”對象時出現以下錯誤。 這個動作是在我的控制器類中完成的:
"org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.billsheng.huddlespringmvc.models.Game; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.billsheng.huddlespringmvc.models.Game"
用戶實體
@Data
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String email;
private String firstName;
private String lastName;
private String password;
private String chosenTeam;
private int gamesPlayed;
private int gamesWon;
@ElementCollection
private List<Game> games = new ArrayList<>();
public User(String firstName, String lastName, String email, String password, String chosenTeam, int gamesPlayed, int gamesWon, ArrayList<Game> games) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.chosenTeam = chosenTeam;
this.gamesPlayed = gamesPlayed;
this.gamesWon = gamesWon;
this.games = games;
}
public User(String firstName, String lastName, String email, String password, String chosenTeam) {
this(firstName, lastName, email, password, chosenTeam, 0, 0, null);
}
public User(int gamesPlayed, int gamesWon, ArrayList<Game> games) {
this.gamesPlayed = gamesPlayed;
this.gamesWon = gamesWon;
this.games = games;
}
public User() {
}
//getters and setters
}
游戲實體
@Data
@Entity
public class Game {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String homeTeam;
private String awayTeam;
private Date date;
private String location;
private String bettingOdds;
private boolean inProgress;
private boolean isReviewed;
//getters and setters
}
我做了一些研究,我相信這個問題源於我在User對象中使用Game對象,但是我不確定具體是什么問題。 感謝所有幫助。
@ElementCollection
不應與實體集合一起使用; 它與@Embeddable
集合@Embeddable
。 如果Thing
是實體,則不要使用@ElementCollection
,而要使用@OneToMany
。
@ElementCollection
:定義基本類型或可嵌入類的實例的集合
您可以使用@OneToMany映射來建立用戶和游戲實體之間的關系。
User.java
@OneToMany(cascade=CascadeType.ALL,fetch= FetchType.LAZY,mappedBy = "user")
private List<Game> games = new ArrayList<>();
//getters and setters
Game.java
@ManyToOne
private User user;
//getters and setters
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.