【发布时间】:2016-12-20 09:00:11
【问题描述】:
得到
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 密钥
我将 lombok 用于 getter 和 setter。
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 :)
}
【问题讨论】:
-
可以添加 DDL 脚本吗?
-
当然是@Rocherlee!
-
你最后的编辑就是我的回答的意思!! :P :)
标签: java spring postgresql hibernate jackson