spring-data-rest integration test fails with simple json request

做~自己de王妃 提交于 2019-12-01 02:43:42

You are correctly associating order with the creator, however the Person is not associated with the orders. You are missing the List<Order> orders field in Person class. Add this, add annotations, add methods for adding order to person and then before sending JSON you should call something like this:

creator.addOrder(order);
order.setCreator(cretr);

Did you try using cascade = CascadeType.ALL in @ManyToOne annotation

public class Order {
    @Id @GeneratedValue//
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)//
    private Person creator;
    private String type;

    public Order(Person creator) {
        this.creator = creator;
    }

    // getters and setters
}

Both your Order and Person classes should implement Serializable to properly break them down into and rebuild them from JSON.

Игорь Добровольський

There are some ways to solve your problem, but I want give you a hint. You just can save only "id" of your person and get the person by "id" from your database, when you need this.

It solves your problem and it also saves the memory.

Alan Hay

I believe you need to do two things to get this work.

  1. Handle the deserialization properly. As you expect Jackson to populate the nested Person object via the constructor you need to annotate this with @JsonCreator. See here:

http://www.cowtowncoder.com/blog/archives/2011/07/entry_457.html

One of more powerful features of Jackson is its ability to use arbitrary >constructors for creating POJO instances, by indicating constructor to use with @JsonCreator annotation ........................................... Property-based creators are typically used to pass one or more obligatory parameters into constructor (either directly or via factory method). If a property is not found from JSON, null is passed instead (or, in case of primitives, so-called default value; 0 for ints and so on).

See also here on why Jackson may not be able to automatically work this out.

https://stackoverflow.com/a/22013603/1356423

  1. Update your JPA mappings. If the associated Person is now populated correctly by the Jackson deserializer then by adding the necessary JPA cascade options to the relationship then both instances should be persisted.

I think then the following should work as expected:

public class Order {

    @Id 
    @GeneratedValue(...)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = cascadeType.ALL)
    private Person creator;

    private String type;

    @JsonCreator
    public Order(@JsonProperty("creator") Person creator) {
        this.creator = creator;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!