Отношение один ко многим не работает! Сущность не сохраняет внешний ключ. Весенний ботинок - PullRequest
1 голос
/ 05 октября 2019

Я новичок в весенней загрузке и связях, и у меня есть данные json, которые передаются в контроллер, а затем у меня есть 3 различных объекта, которые нужно передать, однако данные идут, но в таблице не будет показан внешний ключ ниже, это jsondata` {

"orderId": "ORD00001",
"orderReferenceCode": "ABCD",
"messageId": "EDI238473828384",
"messageType": "MORR",
"messageCreatedAt": "2018-01-10T10:56:00Z",
"shipToLocationId": "34rsdf",
"shipToAddressName": "Test Store",
"shipToAddressLine1": "1 Order Street",
"shipToAddressLine2": "",
"shipToAddressCity": "asdfa",
"shipToAddressState": "sadfasdf",
"shipToAddressPostCode": "423d23",
"shipToAddressCountryCode": "UK",
"shipToDeliverAt": "2016-08-25",
"shipToDeliverLatestAt": "2018-01-12",
"items": [
    {
        "itemId": "106571637",
        "itemLineId": 1,
        "itemBaseType": "skuMin",
        "itemAlternateId": {
            "skuMin": "M104593859",
            "skuPin": "P104593867",
            "skuLegacy": "L0472851",
            "barcodeAsin": "ASIN29384845",
            "barcodeEan": "EAN3928445",

        },
        "itemDescription": "Heinz Baked Beans",
        "quantityType": "unit",
        "quantityOrdered": 30,
        "priceOrderedCurrency": "GBP",
        "priceOrderedAmount": 1.34,
        "priceOrderedTaxRate": 20,

    }
]}

Далее у меня есть 3 сущности для каждой таблицы Item, Order и ItemAlternateId

Order Entity

@Data
@Entity
@NoArgsConstructor
@Table(name = "order_table")
public class Order {

    private @Id
    @GeneratedValue
    long id;
    private String orderId;
    private String orderReferenceCode;
    private String messageId;
    private String messageType;
    private String messageCreatedAt; // Date
    private String shipToLocationId;
    private String shipToAddressName;
    private String shipToAddressLine1;
    private String shipToAddressLine2;
    private String shipToAddressCity;
    private String shipToAddressState;
    private String shipToAddressPostCode;
    private String shipToAddressCountryCode;
    private String shipToDeliverAt; // Date
    private String shipToDeliverLatestAt; // Date
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "orderedBy")
    private List<Item> items;

    public Order(String orderId, String orderReferenceCode, String messageId, String messageType, String messageCreatedAt, String shipToLocationId, String shipToAddressName, String shipToAddressLine1, String shipToAddressLine2, String shipToAddressCity, String shipToAddressState, String shipToAddressPostCode, String shipToAddressCountryCode, String shipToDeliverAt, String shipToDeliverLatestAt, List<Item> items) {
        this.orderId = orderId;
        this.orderReferenceCode = orderReferenceCode;
        this.messageId = messageId;
        this.messageType = messageType;
        this.messageCreatedAt = messageCreatedAt;
        this.shipToLocationId = shipToLocationId;
        this.shipToAddressName = shipToAddressName;
        this.shipToAddressLine1 = shipToAddressLine1;
        this.shipToAddressLine2 = shipToAddressLine2;
        this.shipToAddressCity = shipToAddressCity;
        this.shipToAddressState = shipToAddressState;
        this.shipToAddressPostCode = shipToAddressPostCode;
        this.shipToAddressCountryCode = shipToAddressCountryCode;
        this.shipToDeliverAt = shipToDeliverAt;
        this.shipToDeliverLatestAt = shipToDeliverLatestAt;
        this.items.forEach(item -> item.setOrderedBy(this));
    }
}

Item Entity

@Entity
@NoArgsConstructor
@Data
public class Item {

    private @Id @GeneratedValue long id;
    private String itemId;
    private int itemLineId;
    private String itemBaseType;
    @OneToOne(cascade=CascadeType.ALL)
    private ItemAlternateId itemAlternateId;
    private String itemDescription;
    private String quantityType;
    private int quantityOrdered;
    private String priceOrderedCurrency;
    private double priceOrderedAmount;
    private int priceOrderedTaxRate;
    @ManyToOne
    @JoinColumn(name = "order_id")
    private Order orderedBy;

    public Item(String itemId, int itemLineId, String itemBaseType, ItemAlternateId itemAlternateId, String itemDescription, String quantityType, int quantityOrdered, String priceOrderedCurrency, double priceOrderedAmount, int priceOrderedTaxRate) {
        this.itemId = itemId;
        this.itemLineId = itemLineId;
        this.itemBaseType = itemBaseType;
        this.itemAlternateId = itemAlternateId;
        this.itemDescription = itemDescription;
        this.quantityType = quantityType;
        this.quantityOrdered = quantityOrdered;
        this.priceOrderedCurrency = priceOrderedCurrency;
        this.priceOrderedAmount = priceOrderedAmount;
        this.priceOrderedTaxRate = priceOrderedTaxRate;
    }
}

ItemAlternateId Entity

@Entity
@Data
@NoArgsConstructor
public class ItemAlternateId {
    private @Id @GeneratedValue long id;
    private String skuMin;
    private String skuPin;
    private String skuLegacy;
    private String barcodeAsin;
    private String barcodeEan;
    @OneToOne
    private Item item;
}

Мой OrderController

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;



    @GetMapping("/orders/{id}")
    public Order getOneOrder(@PathVariable Long id) {
        return orderService.getOneOrder(id);
    }

    @PostMapping("/orders")
    public Order newOrder(@RequestBody Order order) {
        return orderService.save(order);
    }
}

В OrderService есть эта функция, которая в основном вызывает интерфейс репозитория, и она просто сохраняет объект.

 public Order save(Order order)
    {
        return orderRepository.save(order);
    }

Все работает, кроме факта, что в таблице Item и ItemAlternateId не сохраняется внешний ключ.

Возвращенный json выглядит следующим образом

{
    "id": 10,
    "orderId": "ORD00001",
    "orderReferenceCode": "ABCD",
    "messageId": "EDI238473828384",
    "messageType": "MORR",
    "messageCreatedAt": "2018-01-10T10:56:00Z",
    "shipToLocationId": "GLN999999",
    "shipToAddressName": "Test Store",
    "shipToAddressLine1": "1 Order Street",
    "shipToAddressLine2": "",
    "shipToAddressCity": "Leeds",
    "shipToAddressState": "West Yorkshire",
    "shipToAddressPostCode": "LS1 9PP",
    "shipToAddressCountryCode": "UK",
    "shipToDeliverAt": "2016-08-25",
    "shipToDeliverLatestAt": "2018-01-12",
    "items": [
        {
            "id": 11,
            "itemId": "106571637",
            "itemLineId": 1,
            "itemBaseType": "skuMin",
            "itemAlternateId": {
                "id": 12,
                "skuMin": "M104593859",
                "skuPin": "P104593867",
                "skuLegacy": "L0472851",
                "barcodeAsin": "ASIN29384845",
                "barcodeEan": "EAN3928445",
                "item": null
            },
            "itemDescription": "Heinz Baked Beans",
            "quantityType": "unit",
            "quantityOrdered": 30,
            "priceOrderedCurrency": "GBP",
            "priceOrderedAmount": 1.34,
            "priceOrderedTaxRate": 20,
            "orderedBy": null
        }
    ]
}

update

Мне удалось решить эту проблему с помощью @JsonManagedReference для отношения один-ко-многим и @JsonBackReference для отношения один-ко-многим, поэтому

Item Entity

    @ManyToOne
    @JoinColumn(name = "order_id")
    @JsonBackReference
    private Order orderedBy;

Заказ субъекта

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "orderedBy")
    @JsonManagedReference
    private List<Item> items;

...