Spring MVC不解析json与数组正确丢失部分数组

时间:2016-01-19 20:34:39

标签: java json spring jhipster

我正在使用jhipster写一个在线蛋糕店。

它有几个类:CakeOrderCakeOrderItemsUserCakeCakeItemAddressCakeOrder有一个User,一个Address和多个CakeOrderItems

类CakeOrder看起来像这样:

@Entity
@Table(name = "cake_order")
public class CakeOrder implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "order_date")
    private ZonedDateTime orderDate;

    @Column(name = "ship_date")
    private ZonedDateTime shipDate;

    @Enumerated(EnumType.STRING)
    @Column(name = "status")
    private CakeOrderStatus status;

    @OneToMany(mappedBy = "cakeOrder")
    // @JsonIgnore
    private Set<CakeOrderItem> cakeOrderItems = new HashSet<>();

    @ManyToOne
    @JoinColumn(name = "address_id")
    private Address address;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;
    // ...
}

一切正常但 createCakeOrder 。这是代码。

/**
 * POST  /cakeOrders -> Create a new cakeOrder.
 */
@RequestMapping(value = "/cakeOrders",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
//
public ResponseEntity<CakeOrder> createCakeOrder(@RequestBody CakeOrder cakeOrder) throws URISyntaxException {
    if (cakeOrder.getId() != null) {
        return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("cakeOrder", "idexists", "A new cakeOrder cannot already have an ID")).body(null);
    }
    // TODO: use transaction
    // Create CakeOrder
    CakeOrder result = cakeOrderRepository.save(cakeOrder);
    // Create CakeOrderItems belonging to that CakeOrder
    for(CakeOrderItem item : cakeOrder.getCakeOrderItems()){
        item.setCakeOrder(order);
        cakeOrderItemRepository.save(item);

    }
    return ResponseEntity.created(new URI("/api/cakeOrders/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert("cakeOrder", result.getId().toString()))
        .body(result);
}

我将以下Json对象作为命令发布到该控制器。

这是订单对象:

{
    "address": {
        "id": 1
    },
    "user": {
        "id": 5
    },
    "cakeOrderItems": [
        {
            "cakeItem": {
                "id": 4
            },
            "unitPrice": 268,
            "quantity": 1
        },
        {
            "cakeItem": {
                "id": 10
            },
            "unitPrice": 175,
            "quantity": 1
        },
        {
            "cakeItem": {
                "id": 18
            },
            "unitPrice": 58,
            "quantity": 1
        }
    ]
}

嗯,这是问题所在。在控制器中,cakeOrder只获得一个CakeOrderItem,而json对象中只有三个。

是错误还是错误配置?我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:4)

对于CakeOrderItem类,您可能希望实现equals和hashcode方法。您正在使用Set,因此当您插入数据时,HashSet的实现将检查是否已经存在任何其他相等的对象。如果是,则不会插入新数据。

检查有关框架背后发生的事情的答案(使用延迟加载和代理对象):What issues should be considered when overriding equals and hashCode in Java?

您还可以获得有关equals和hashcode的更多详细信息。