【问题标题】:Null constraint on One to many hibernate一对多休眠的空约束
【发布时间】: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


【解决方案1】:

我猜你必须单独保存Tournament实体,然后在相应的Group实体中设置Tournament,然后单独保存Groupentity。 (无论是spring保存组实体还是通过映射对应的Tournament来保存组实体,插入语句的数量保持不变。)

这里发生的情况是,您期望 Spring 通过调用 Group 的 setter 将每个 Tournament 映射到 Group,但这并没有发生。

【讨论】:

  • 是的,我之前在 jooq 中使用过这种方法,看过多个关于此的博客条目,如果能将整个对象图保存在“一个”中会很好,我不知道如何hibernate 处理批量插入,但对于这个小型应用程序,一次繁重的查询现在不会成为问题 :)
猜你喜欢
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多