How can I send data in POST body without setting the auto generated primary key values in Spring Boot?

不想你离开。 提交于 2020-05-17 07:43:11

问题


I have two classes/tables--- Customer and Address having a bi-directional one-to-one relationship. Address_id is the foreign key.

Here is the entity diagram

I am trying to send data through postman, but I want to send the values without setting the primary key attributes in the post body. It is working if I omit the id attribute in for customer only. But its not working if i do the same for address.

This is the post body for which data is successfully getting inserted.

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

if I omit the <id></id> in addressdto then I am getting this error in postman--

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

Error in console--

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

Please tell me what is the correct way to do so, I do not think that we need to provide the id fields. How can I approach this? In the EntityToDtoMapper mapToEntity() method if I omit the setId() from addressDto then it won't work at all.

Address Entity

@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

Customer Entity

@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

回答1:


Add the @GeneratedValue to your id fields to correctly auto-generate the entity IDs. Please change

@Id
private int id;

to

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

on both of your entities.

Then in your mapToEntity method add the line:

address.setCustomer(customer);




回答2:


Change your Customer Entity by adding a new field variable as addressId

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

    @Column(name="address_id")
    private int addressId;

    @Temporal(TemporalType.TIMESTAMP)
    private Date date;

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

    public Customer() {
        super();
    }
}

And change EntityDTOMapper as below

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.setAddressId(customerDto.getAddressdto().getId());
    //customer.setAddress(address);

    return customer;    
}


来源:https://stackoverflow.com/questions/61393839/how-can-i-send-data-in-post-body-without-setting-the-auto-generated-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!