简体   繁体   中英

Hibernate, Saving new entity without fetching associated entities

I'm using spring boot and hibernate, trying to save an entity with a @ManyToOne relation by posting only the id of the referenced entity

@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;

    ...
}

And the controller code is similar to:

@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);
    }
}

And the posted JSON is similar to

{
    "bar" : 1
}

However I'm getting an error in jackson while deserializing

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

You either change your json so that you provide an object type for bar field where Jackson expects it, instead of an integer, and pass id explicitly:

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

OR

Create the corresponding setter inside your Foo class - a setter that has the same input type as the ID type - in your case an integer:

public class Foo implements Serializable {
    ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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