[英]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.