【问题标题】:How to update data from json using spring boot如何使用spring boot从json更新数据
【发布时间】:2021-07-05 15:27:19
【问题描述】:

我从一个名为“Person”的对象创建了一个表,我可以从 Postman 发布、删除和放置。我对如何从我在邮递员中输入的 JSON 创建新查询没有任何问题。但是,每当我尝试删除或更新(使用 put)我的查询时,我都会使用 @PathVariable 选择我想要的查询,并使用 @RequestVariable 更新选定的数据。但我希望能够从 JSON 文件中删除或更新。这是我的代码的样子。

人物对象

@Entity
@Table(name="person")
public class Person {
    @Id
    @SequenceGenerator(
            name = "person_sequence",
            sequenceName = "person_sequence",
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "person_sequence"
    )
    @Column(name="id")
    private Long id;
    private String name;
    private String lastname;
}
//Getters, Setters, Constructors and ToString is here

人员控制器

@RestController
@RequestMapping(path = "api/v1/person")
public class PersonController {

    private final PersonService personService;

    @Autowired
    public PersonController(PersonService personService) {
        this.personService = personService;
    }
    //@GetMapping
    //@PostMapping

    @DeleteMapping(path = "{personId}")
    public void deletePerson(@PathVariable("personId") Long personId{
        personService.deletePerson(personId);
    }

    @PutMapping(path = "{personId}")
    public void updatePerson(@PathVariable("personId") Long personId,
                              @RequestParam(required = false) String name,
                              @RequestParam(required = false) String lastname){
        personService.updatePersonService(personId, name, lastname);
    }
}

这是我的 PersonRepository 接口

@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
}

我对 Spring Boot 很陌生。如果我能在@PutMapping 和@DeleteMapping 中得到一个代码,以及代码在PersonService 类中的请求中的样子,那就太好了。

【问题讨论】:

    标签: java postgresql spring-boot spring-data-jpa postman


    【解决方案1】:

    在请求正文中使用 delete 方法并不常见,相反,您可以使用 put 方法。此外,最好为 JSON 序列化创建单独的 (Dto) 对象。

    @PutMapping()
    public void deletePerson(@RequestBody PersonDto person){
        personService.deletePerson(person.getId());
    }
    

    此外,如果您想创建或更新实体,可以使用请求正文。

    @PutMapping(path = "{personId}")
    public void updatePerson(@PathVariable("personId") Long personId, @RequestBody PersonDto person){
        personService.updatePersonService(personId, person);
    }
    

    【讨论】:

      【解决方案2】:

      所以您想用“json 内容”替换您的 RequestParams,对吗? 如果是这样,你可以使用这个:

      @Valid @RequestBody final Person person
      

      顺便说一句,保留您的删除方法,在删除中使用实体的 id 就足够了,不需要有请求正文

      附:我将创建 1 个新实体 PersonDTO 并将其用于控制​​器/服务组件,并将您的 Person 重命名为 PersonDAO 并仅将其用于存储库组件

      【讨论】:

      • 我确实有一个@Service 类。我没有添加它,因为我想知道它是如何实现的。对不起,我对springboot很陌生。
      • 别担心,这只是一个建议 - 为应用程序的不同层设置单独的实体
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 2019-06-15
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多