繁体   English   中英

空对一对多休眠的约束

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM