如何在POST正文中发送数据而无需在Spring Boot中设置自动生成的主键值? [英] How can I send data in POST body without setting the auto generated primary key values in Spring Boot?

查看:143
本文介绍了如何在POST正文中发送数据而无需在Spring Boot中设置自动生成的主键值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是实体图

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

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>

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

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

控制台错误-

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

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

addressDto

public class AddressDto {

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


    public AddressDto() {
        super();
    }

EntityToDtoMapper

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

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(),那么它将根本无法工作.

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.

地址实体

@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

推荐答案

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

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

@Id
private int id;

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

在两个实体上

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

Then in your mapToEntity method add the line:

address.setCustomer(customer);

这篇关于如何在POST正文中发送数据而无需在Spring Boot中设置自动生成的主键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆