首页 > 解决方案 > 使用 @EmbeddedId 的多对多关系生成为:class 生成的空 id

问题描述

我有两个表,它们之间存在多对多关系:

条目表使用@EmbeddedId

@Getter @Setter
@AllArgsConstructor
@NoArgsConstructor
public class Entry {

    @EmbeddedId
    EntryKey id;

    @ManyToOne
    @MapsId("competition_id")
    @JoinColumn(name = "competition_id")
    private Competition competition;

    @ManyToOne
    @MapsId("user_id")
    @JoinColumn(name = "user_id")
    private User user;

    private Integer number;
}

其中EntryKey实现为:

@EqualsAndHashCode
@Getter @Setter
@AllArgsConstructor
@NoArgsConstructor
public class EntryKey implements Serializable {
    @Column(name = "competition_id")
    Integer competitionId;

    @Column(name = "user_id")
    Integer userId;
}

和实体CompetitionUser包含反向引用:

竞赛

@OneToMany(mappedBy = "competition")
private Set<Entry> entries;

用户

@OneToMany(mappedBy = "user")
private Set<Entry> entries;

问题是在执行以下发布请求时(也许这是错误的?):

{
    "user_id": 1,
    "competition_id": 2,
    "number": 1
}

...正在此控制器中拾取:

@PostMapping
public Entry create(@RequestBody Entry entry) {
    return entryRepo.save(entry);
}

AIdentifierGenerationException被抛出:org.hibernate.id.IdentifierGenerationException: null id generated for:class com.mw.API.Entities.Entry。我不确定我要去哪里错了。

这里有一个非常相似的问题但是似乎没有一个答案有帮助。

标签: hibernatespring-bootjpaspring-data-jpa

解决方案


似乎 EntryKey 没有被请求绑定。发送这个

{
    "competition":{
            "competitionId":6   
    },
    "user":{
        "userId":5
    },
    "number": 1
}

而不是这个

{
    "user_id": 1,
    "competition_id": 2,
    "number": 1
}

应该正确绑定值。


推荐阅读