![](/img/trans.png)
[英]Spring-Hibernate: Insertion error, not-null constraint (One-to-many relationship)
[英]Null constraint on One to many hibernate
入門
org.postgresql.util.PSQLException: ERROR: null value in column "tournament_id" violates not-null constraint`
Tournament.java
@Data
@Entity
public class Tournament {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToMany(mappedBy = "tournament", cascade = CascadeType.PERSIST)
private List<Group> groups;}
組
@Entity
@Data
@Table(schema = "offan", name = "groups")
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name = "tournament_id")
private Tournament tournament;
public Group(){}
public Group(Tournament tournament){
this.tournament = tournament;
}
}
我正努力一舉兩得。 與CrudRepository
。 僅保存沒有任何組的錦標賽實例就可以了。 我看不到為什么組沒有正確插入Tournament_id鍵
我正在使用龍目島吸氣劑和二傳手。
DDL:
CREATE TABLE tournaments (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE groups (
id SERIAL PRIMARY KEY,
name VARCHAR(50) ,
tournament_id INTEGER REFERENCES tournaments (id) NOT NULL ,
UNIQUE (name, tournament_id)
);
我使用Spring @RequestBody
會將我的對象解析為Tournament對象,這可能無法正確設置映射?
使用基礎的傑克遜庫解析對象未設置正確的映射。 手動執行所有操作均正確插入。
@RequestMapping(value = "/tournaments", method = RequestMethod.POST)
public Tournament createTournament(@RequestBody Tournament tournament){
//Will not work
//Tournament savedEntry = tournamentRepository.save(tournament);
//
//Setting properties manually works...
Tournament t = new Tournament();
t.setName(tournament.getName());
Group group = new Group();
group.setTournament(t);
t.getGroups().add(group)
// Both tournament and group are inserted
t = tournamentRepository.save(t);
return t; //Overflow here because of jackson another thing to fix :)
}
我猜您將必須分別保存Tournament
實體,然后在相應的Group
實體中設置該Tournament
,然后分別保存該Group
實體。 (在彈簧保存組實體的情況下,或者通過映射相應的Tournament
保存組實體,insert語句的數量都保持不變。)
這里發生的事情是您期望Spring通過調用Group
的設置者將每個Tournament
映射到Group
,但是這沒有發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.