Hibernate,保存新实体而不提取关联实体

时间:2016-08-19 20:20:13

标签: java hibernate spring-boot jackson

我使用spring boot和hibernate,尝试通过仅发布引用实体的id来保存具有@ManyToOne关系的实体

@Entity
@Table(name = "foo_table")
public class Foo implements Serializable {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private id;

    @NotNull
    @JsonIdentityReference(alwaysAsId=true)
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "bar_id", nullable = false)
    private Bar bar;

    ...
}


@Entity
@Table(name = "bar_table")
public class Bar implements Serializable {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "bar")
    private Set<Foo> foos;

    ...
}

控制器代码类似于:

@RestController
public class FooController {

    @Autowired
    private FooRepo fooRepo;

    @RequestMapping(value = "/foo", method= RequestMethod.POST)
    public Foo foo(@RequestBody @Valid Foo foo)
        throws Exception {
        return fooRepo.save(foo);
    }
}

发布的JSON类似于

{
    "bar" : 1
}

然而,我在反序列化时遇到了杰克逊的错误

"Could not read document: Unresolved forward references for: Object id [1]"

1 个答案:

答案 0 :(得分:2)

您要么更改您的json,以便为杰克逊期望的bar字段提供对象类型,而不是整数,并明确传递id

{
    "bar": {
        "id": 1
    }
}

OR

在你的Foo类中创建相应的setter - 一个与ID类型具有相同输入类型的setter - 在你的情况下是一个整数:

public class Foo implements Serializable {
    ...

    @JsonProperty("bar")
    public void setBar(int id) {
        // For example:
        this.bar = new Bar(id);
    }
}