发布数据时为空

getting null while posting data(发布数据时为空)

本文介绍了发布数据时为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用邮递员来处理 spring boot api.目前我正在尝试将数据添加到相关表中.其中有2个地区和城镇.城镇有一个 regionid 列.这是我的要求.

I am using a postman to work with spring boot api. Currently I am trying to add data to a related table. There are 2 of them regions and towns. Towns has a regionid column. Here is my request.

{
"name": "test",
"regionid":"2"
}

虽然名称发布得很好,但区域 ID 为空.我正在尝试在控制器中打印出来.这是它的保存数据方法:

While name is posting just fine, region id is null. I am trying to print it out in a controller. Here is a save data method of it:

@PostMapping("/add")
    public ResponseEntity<Towns> createtown(@RequestBody Towns town) {
      try {
            
          Towns _town = townsrepository
            .save(new Towns( town.getName(), town.getRegionid()));
        return new ResponseEntity<>(_town, HttpStatus.CREATED);
      } catch (Exception e) {
       System.out.println(e.getMessage());
        System.out.println("region");
        System.out.println(town.getRegionid());
    
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }

我遇到了异常,在打印 town.getName() 时我得到了测试.但是,当我尝试打印出 town.getRegionId() 时,我得到了空值.这是我的模型类

I am getting the exception and while I am printing town.getName() I get test. But while I try to print out town.getRegionId() I get null. Here is my model class

package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
@Entity
@Table(name = "towns")

public class Towns {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column(name = "name")
    private String name;
     @ManyToOne(fetch = FetchType.LAZY, optional = false)
        @JoinColumn(name = "regionid", nullable = false)
        @OnDelete(action = OnDeleteAction.CASCADE)
        private Regions regionid;
    
    public Towns() {

    }
    public Towns(String name,Regions regionid) {
    //  super();
        this.id=id;
        this.name = name;
        this.regionid=regionid;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        
        this.name = name;
    }
    public Regions getRegionid() {
        return regionid;
    }
    public void setRegionid(Regions regionid) {
        this.regionid = regionid;
    }
    
}

还有存储库:

package com.example.repository;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;

import com.example.model.Towns;
import com.example.model.Regions;
public interface TownsRepository extends JpaRepository<Towns, Integer> {

     List<Towns> findByNameContaining(String name);
     Page<Regions> findByregionid(Integer regionid, Pageable pageable);
        Optional<Regions> findByregionidAndId(Integer regionId, Integer id);

}

还有 Application.properties 以防万一

And Application.properties in case it will help

spring.datasource.url= jdbc:mysql://localhost:3306/appartmentbuilderbase?useSSL=false
spring.datasource.username= root
spring.datasource.password=
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto= update

我在这里做错了什么?

尝试按照建议进行:

Towns _town = townsrepository .save(new Towns( town.getName(), regionsrepository.findById(town.getRegionid())));

得到了这些错误:

Description Resource    Path    Location    Type
The constructor Towns(String, Optional<Regions>) is undefined   TownsController.java    /apartmentbuilders/src/main/java/com/example/controller line 71 Java Problem

还有这个:

Description Resource    Path    Location    Type
The method save(S) in the type CrudRepository<Towns,Integer> is not applicable for the arguments (Towns)    TownsController.java    /apartmentbuilders/src/main/java/com/example/controller line 71 Java Problem

添加完整的控制器代码

package com.example.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.Towns;
import com.example.repository.TownsRepository;
import com.example.repository.RegionsRepository;
@CrossOrigin(origins = "http://localhost:8081")

@RestController
@RequestMapping("/towns")

public class TownsController {

    @Autowired
    TownsRepository townsrepository;
    @Autowired
    RegionsRepository regionsrepository;
    @GetMapping("/list")
    public ResponseEntity<List<Towns>> getAllTowns(@RequestParam(required = false) String name) {
      try {
        List<Towns> towns = new ArrayList<Towns>();

        if (name == null)
          townsrepository.findAll().forEach(towns::add);
        else
          townsrepository.findByNameContaining(name).forEach(towns::add);

        if (towns.isEmpty()) {
          return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }

        return new ResponseEntity<>(towns, HttpStatus.OK);
      } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
    
    @GetMapping("/list/{id}")
    public ResponseEntity<Towns> getTownById(@PathVariable("id") int id) {
      Optional<Towns> townData = townsrepository.findById(id);

      if (townData.isPresent()) {
        return new ResponseEntity<>(townData.get(), HttpStatus.OK);
      } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
      }
    }

    @PostMapping("/add")
    public ResponseEntity<Towns> createtown(@RequestBody Towns town) {
      try {
            
          Towns _town = townsrepository
            .save(new Towns( town.getName(), town.getRegionid()));
         // Towns _town = townsrepository .save(new Towns( town.getName(), regionsrepository.findByRegionId(town.getRegionid())));
          return new ResponseEntity<>(_town, HttpStatus.CREATED);
      } catch (Exception e) {
       System.out.println(e.getMessage());
        System.out.println("region");
        System.out.println(town.getRegionid());
    
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
    
    @PutMapping("/edit/{id}")
    public ResponseEntity<Towns> updateTown(@PathVariable("id") int id, @RequestBody Towns town) {
      Optional<Towns> townData = townsrepository.findById(id);

      if (townData.isPresent()) {
        Towns _town = townData.get();
        _town.setName(town.getName());
        _town.setRegionid(town.getRegionid());
        return new ResponseEntity<>(townsrepository.save(_town), HttpStatus.OK);
      } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
      }
    }
    
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<HttpStatus> deleteTown(@PathVariable("id") int id) {
      try {
        townsrepository.deleteById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
      } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
}
     

添加区域存储库

package com.example.repository;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.model.Regions;

public interface RegionsRepository extends JpaRepository<Regions, Integer> {

      List<Regions> findByNameContaining(String name);

}

推荐答案

你缺少一个 DTO 类.不要直接将 DB 实体类映射到请求正文.有一个类似的课程

You are missing a DTO class. Don't directly map DB entity class to request body. have a class like

@Data
public class TownDTO {
   private String name;
   private String regionid;
}

同样在保存时,通过存储库获取区域:

also when saving, get the region through a repository:

Towns _town = townsrepository
  .save(new Towns( town.getName(), regionRepository.findByRegionId(town.regionId)));

所以在控制器中:

@PostMapping("/add")
public ResponseEntity<Towns> createtown(@RequestBody Town town) {
  try {
        
      Towns _town = townsrepository
        .save(new Towns( town.getName(), regionRepository.findByRegionId(town.regionId)));
    return new ResponseEntity<>(_town, HttpStatus.CREATED);
  } catch (Exception e) {
   System.out.println(e.getMessage());
    System.out.println("region");
    System.out.println(town.getRegionid());

    return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
  }
}

这篇关于发布数据时为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:发布数据时为空

基础教程推荐