我如何在POST正文中发送数据而不在Spring Boot中设置自动生成的主键值?

问题描述 投票:0回答:1

我有两个类/表--客户和地址具有一对一的双向关系。 Address_id是外键。

这里是实体图

enter image description here

我正在尝试通过邮递员发送数据,但是我想发送值而不在邮递正文中设置主键属性。如果我只为客户省略id属性,则此方法有效。 但是如果我对地址做同样的操作,则不起作用。

这是已成功为其插入数据的帖子正文。

<Customer>
<firstName>Dave</firstName>
<lastName>Bautista</lastName>
<gender>M</gender>
<date>2012-01-26T09:00:00.000+0000</date>
<addressdto>
<id>7</id>
<city>BANKURA</city>
<country>WEST BENGAL</country>
</addressdto>
</Customer>

[如果我省略了<id></id>中的addressdto,那么我在邮递员中收到此错误-

Failed to add customer due to could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

控制台错误-

2020-04-23 23:10:12.093 ERROR 3824 --- [io-8080-exec-10] o.h.engine.jdbc.spi.SqlExceptionHelper   : 
Cannot add or update a child row
: a foreign key constraint fails (`liqbtest`.`customers`, CONSTRAINT `FK_DETAIL` FOREIGN KEY 
(`address_id`) REFERENCES `address` (`id`))

CustomerDto

package com.spring.liquibase.demo.dto;

import java.util.Date;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.sun.xml.txw2.annotation.XmlElement;


@JacksonXmlRootElement(localName = "Customer")
public class CustomerDto {

    private int id;
    private String firstName;
    private String lastName;
    private String gender;
    private Date date;
    private AddressDto addressdto;


    public CustomerDto() {
        super();
    }
..getters and setters

addressDto

public class AddressDto {

    private int id;
    private String city;
    private String country;


    public AddressDto() {
        super();
    }

EntityToDtoMapper

public Customer mapToEntity(CustomerDto customerDto) {
        Address address=new Address();
        address.setCity(customerDto.getAddressdto().getCity());
        address.setCountry(customerDto.getAddressdto().getCountry());
        address.setId(customerDto.getAddressdto().getId());

        Customer customer=new Customer();
        customer.setId(customerDto.getId());
        customer.setFirstName(customerDto.getFirstName());
        customer.setLastName(customerDto.getLastName());
        customer.setGender(customerDto.getGender());
        customer.setDate(customerDto.getDate());
        customer.setAddress(address);
        return customer;    
    }

HomeController

@PostMapping("/customer")
     public ResponseEntity<String> addCustomer(@RequestBody CustomerDto customerDto){
        String message="";
        ResponseEntity<String> finalMessage=null;
        try {

        Customer customer=mapper.mapToEntity(customerDto);
        customerService.addCustomer(customer);
        message="Customer with "+customer.getId()+" sucessfully added";
        finalMessage= new ResponseEntity<>(message, HttpStatus.OK);

    }catch(Exception e) {
        message="Failed to add customer due to "+e.getMessage();
        finalMessage= new ResponseEntity<>(message, HttpStatus.NOT_ACCEPTABLE);
    }
        return finalMessage;
    }

请告诉我这样做的正确方法是什么,我认为我们不需要提供id字段。我该如何处理?在EntityToDtoMapper mapToEntity()方法中,如果我从addressDto省略了setId(),那么它将根本无法使用。

地址实体

@Entity
public class Address {
    @Id
    private int id;
    private String city;
    private String country; 
    @OneToOne(mappedBy="address",cascade=CascadeType.ALL)
    private Customer customer;
    public Address() {
        super();
    }
    ...getters and setters

客户实体

@Entity
@Table(name="customers")
public class Customer {

    @Id
    private int id;
    @Column(name="first_name")
    private String firstName;
    @Column(name="last_name")
    private String lastName;
    private String gender;

    @Temporal(TemporalType.TIMESTAMP)
    private Date date;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="address_id")
    private Address address;

    public Customer() {
        super();
    }
...getters an setters
hibernate spring-boot post postman hibernate-mapping
1个回答
0
投票

@GeneratedValue添加到您的ID字段中以正确自动生成实体ID。请更改

@Id
private int id;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)

在您两个实体上。

然后在mapToEntity方法中添加以下行:

address.setCustomer(customer);

© www.soinside.com 2019 - 2024. All rights reserved.