当前位置: 首页 > 知识库问答 >
问题:

在Postman中输出Spring靴反向

章琛
2023-03-14
{
    "name": "Frizzle",
    "dateOfBirth": "2019-07-27",
    "weight": 7.1,
    "breed": "Birman",
    "firstVaccination": "yes",
    "secondVaccination": "yes",
    "breedPrice": 8000,
    "firstVaccinationPrice": 80.50,
    "secondVaccinationPrice": 80.10
}
{
        "id": 3,
        "name": null,
        "dateOfBirth": null,
        "weight": 0.0,
        "breed": null,
        "firstVaccination": null,
        "secondVaccination": null,
        "fileUpload": null,
        "price": {
            "id": 3,
            "broadPrice": 8000.0,
            "firstVaccinationPrice": 80.5,
            "secondVaccinationPrice": 80.1,
            "totalPrice": 8160.6
        }
}

我的档案是这样的。

Kitten.java

import com.sun.istack.NotNull;

import javax.persistence.*;
import java.time.LocalDate;

@Entity
@Table(name = "kittens")
public class Kitten {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @NotNull
    private String name;

    @NotNull
    @Column(name = "date_of_birth")
    private LocalDate dateOfBirth;

    @NotNull
    @Column
    private double weight;

    @NotNull
    @Column(name = "breed")
    private String breed;

    @Column(name = "first_vaccination")
    private String firstVaccination;

    @Column(name = "second_vaccination")
    private String secondVaccination;

    @OneToOne(mappedBy = "kitten")
    private FileUpload fileUpload;

    @OneToOne(fetch = FetchType.LAZY,
            mappedBy = "kitten")
    private Price price;

    public Kitten(String name, LocalDate dateOfBirth, double weight, String breed, String firstVaccination, String secondVaccination) {
    }

    public Kitten() {

    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public LocalDate getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(LocalDate dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getFirstVaccination() {
        return firstVaccination;
    }

    public void setFirstVaccination(String firstVaccination) {
        this.firstVaccination = firstVaccination;
    }

    public String getSecondVaccination() {
        return secondVaccination;
    }

    public void setSecondVaccination(String secondVaccination) {
        this.secondVaccination = secondVaccination;
    }

    public FileUpload getFileUpload() {
        return fileUpload;
    }

    public void setFileUpload(FileUpload fileUpload) {
        this.fileUpload = fileUpload;
    }

    public Price getPrice() {
        return price;
    }

    public void setPrice(Price price) {
        this.price = price;
    }
}

price.java

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sun.istack.NotNull;

import javax.persistence.*;

@Entity
@Table(name = "prices")
public class Price {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @NotNull
    @Column(name = "breed_price")
    private double breedPrice;

    @Column(name = "first_vaccination_price")
    private double firstVaccinationPrice;

    @Column(name = "second_vaccination_price")
    private double secondVaccinationPrice;

    @JsonIgnore
    @OneToOne(fetch = FetchType.LAZY,
            cascade = CascadeType.ALL,
            orphanRemoval = true)
    @JoinColumn(name = "kitten_id")
    private Kitten kitten;

    public Price() {

    }

    public Price(double breedPrice, double firstVaccinationPrice, double secondVaccinationPrice) {
        this.breedPrice = breedPrice;
        this.firstVaccinationPrice = firstVaccinationPrice;
        this.secondVaccinationPrice = secondVaccinationPrice;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public double getBreedPrice() {
        return breedPrice;
    }

    public void setBreedPrice(double breedPrice) {
        this.breedPrice = breedPrice;
    }

    public double getFirstVaccinationPrice() {
        return firstVaccinationPrice;
    }

    public void setFirstVaccinationPrice(double firstVaccinationPrice) {
        this.firstVaccinationPrice = firstVaccinationPrice;
    }

    public double getSecondVaccinationPrice() {
        return secondVaccinationPrice;
    }

    public void setSecondVaccinationPrice(double secondVaccinationPrice) {
        this.secondVaccinationPrice = secondVaccinationPrice;
    }

    public Kitten getKitten() {
        return kitten;
    }

    public void setKitten(Kitten kitten) {
        this.kitten = kitten;
    }

    public Double getTotalPrice() {
        return this.getBreedPrice() + this.getFirstVaccinationPrice() + this.getSecondVaccinationPrice();
    }
}
import nl.danielle.cattery.payload.KittenRequest;

import java.time.LocalDate;

public class KittenBuilder {

    //Kitten    
    private String name;
    private LocalDate dateOfBirth;
    private double weight;
    private String breed;
    private String firstVaccination;
    private String secondVaccination;

    //Price
    private double breedPrice;
    private double firstVaccinationPrice;
    private double secondVaccinationPrice;

    public KittenBuilder(KittenRequest kittenRequest) {
        this.name = kittenRequest.getName();
        this.dateOfBirth = kittenRequest.getDateOfBirth();
        this.weight = kittenRequest.getWeight();
        this.breed = kittenRequest.getBreed();
        this.firstVaccination = kittenRequest.getFirstVaccination();
        this.secondVaccination = kittenRequest.getSecondVaccination();
        this.breedPrice = kittenRequest.getBreedPrice();
        this.firstVaccinationPrice = kittenRequest.getFirstVaccinationPrice();
        this.secondVaccinationPrice = kittenRequest.getSecondVaccinationPrice();
    }

    public Kitten buildKitten() {
        return new Kitten(name, dateOfBirth, weight, breed, firstVaccination, secondVaccination);
    }

    public Price buildPrice() {
        return new Price(breedPrice, firstVaccinationPrice, secondVaccinationPrice);
    }
}
import com.sun.istack.NotNull;

import java.time.LocalDate;

public class KittenRequest {
    //Kitten
    @NotNull
    private String name;
    @NotNull
    private LocalDate dateOfBirth;
    @NotNull
    private double weight;
    @NotNull
    private String breed;
    private String firstVaccination;
    private String secondVaccination;

    //Price
    @NotNull
    private double breedPrice;
    private double firstVaccinationPrice;
    private double secondVaccinationPrice;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public LocalDate getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(LocalDate dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getFirstVaccination() {
        return firstVaccination;
    }

    public void setFirstVaccination(String firstVaccination) {
        this.firstVaccination = firstVaccination;
    }

    public String getSecondVaccination() {
        return secondVaccination;
    }

    public void setSecondVaccination(String secondVaccination) {
        this.secondVaccination = secondVaccination;
    }

    public double getBreedPrice() {
        return breedPrice;
    }

    public void setBreedPrice(double breedPrice) {
        this.breedPrice = breedPrice;
    }

    public double getFirstVaccinationPrice() {
        return firstVaccinationPrice;
    }

    public void setFirstVaccinationPrice(double firstVaccinationPrice) {
        this.firstVaccinationPrice = firstVaccinationPrice;
    }

    public double getSecondVaccinationPrice() {
        return secondVaccinationPrice;
    }

    public void setSecondVaccinationPrice(double secondVaccinationPrice) {
        this.secondVaccinationPrice = secondVaccinationPrice;
    }
}
import nl.danielle.cattery.model.FileUpload;
import nl.danielle.cattery.payload.KittenRequest;
import nl.danielle.cattery.payload.ResponseMessage;
import nl.danielle.cattery.service.FileStorageServiceImpl;
import nl.danielle.cattery.service.KittenService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;

@RestController
@RequestMapping(value = "/kittens")
public class KittenController {

    final KittenService kittenService;

    final FileStorageServiceImpl storageService;

    public KittenController(KittenService kittenService, FileStorageServiceImpl storageService) {
        this.kittenService = kittenService;
        this.storageService = storageService;
    }

    @GetMapping(value = "")
    public ResponseEntity<Object> getKittens() {
        return ResponseEntity.ok().body(kittenService.getKittens());
    }

    @GetMapping(value = "/{id}")
    public ResponseEntity<Object> getKitten(@PathVariable("id") long id) {
        return ResponseEntity.ok().body(kittenService.getKittenById(id));
    }

    @PostMapping(value = "/add")
    public ResponseEntity<Object> saveKitten(@RequestBody KittenRequest kitten) {
        long newId = kittenService.saveKitten(kitten);

        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(newId).toUri();

        return ResponseEntity.created(location).build();
    }

    @PutMapping(value = "/{id}")
    public ResponseEntity<Object> updateKitten(@PathVariable("id") long id, @RequestBody KittenRequest kitten) {
        kittenService.updateKitten(id, kitten);
        return ResponseEntity.noContent().build();
    }

    @PutMapping(value = "/{id}/price")
    public ResponseEntity<Object> updatePrice(@PathVariable("id") long id, @RequestBody KittenRequest price) {
        kittenService.updatePrice(id, price);
        return ResponseEntity.noContent().build();
    }

    @DeleteMapping(value = "/{id}")
    public ResponseEntity<Object> deleteKitten(@PathVariable("id") long id) {
        kittenService.deleteKitten(id);
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/upload/kittenid/{id}")
    public ResponseEntity<ResponseMessage> uploadFile(@PathVariable long id, @RequestParam("file") MultipartFile file) {

        try {
            storageService.store(file, id);

            String message = "Uploaded the file successfully: " + file.getOriginalFilename();
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));

        } catch (Exception e) {
            String message = "Could not upload the file: " + file.getOriginalFilename() + "!";
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
        }
    }

    @GetMapping("/download/{id}")
    public ResponseEntity<byte[]> getFileById(@PathVariable("id") String id) {
        FileUpload fileUpload = storageService.getFileById(id);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileUpload.getName() + "\"")
                .body(fileUpload.getData());
    }
}

KittenService.java

package nl.danielle.cattery.service;

import nl.danielle.cattery.exceptions.DatabaseErrorException;
import nl.danielle.cattery.exceptions.RecordNotFoundException;
import nl.danielle.cattery.model.Kitten;
import nl.danielle.cattery.model.KittenBuilder;
import nl.danielle.cattery.model.Price;
import nl.danielle.cattery.payload.KittenRequest;
import nl.danielle.cattery.repository.KittenRepository;
import nl.danielle.cattery.repository.PriceRepository;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service
public class KittenServiceImpl implements KittenService {

    final KittenRepository kittenRepository;

    final PriceRepository priceRepository;

    public KittenServiceImpl(KittenRepository kittenRepository, PriceRepository priceRepository) {
        this.kittenRepository = kittenRepository;
        this.priceRepository = priceRepository;
    }

    @Override
    public Collection<Kitten> getKittens() {
        return kittenRepository.findAll();
    }

    @Override
    public Kitten getKittenById(long id) {
        if (!kittenRepository.existsById(id)) {
            throw new RecordNotFoundException();
        }
        return kittenRepository.findById(id).orElse(null);
    }

    @Override
    public long saveKitten(KittenRequest kittenRequest) {

        Kitten newKitten = new KittenBuilder(kittenRequest).buildKitten();
        Price newPrice = new KittenBuilder(kittenRequest).buildPrice();

        Price savedPrice = priceRepository.save(newPrice);
        newKitten.setPrice(savedPrice);
        newPrice.setKitten(newKitten);

        return kittenRepository.save(newKitten).getId();
    }

    @Override
    public void updateKitten(long id, KittenRequest kitten) {
        if (kittenRepository.existsById(id)) {
            try {
                Kitten existingKitten = kittenRepository.findById(id).orElse(null);
                existingKitten.setName(kitten.getName());
                existingKitten.setDateOfBirth(kitten.getDateOfBirth());
                existingKitten.setWeight(kitten.getWeight());
                existingKitten.setBreed(kitten.getBreed());
                existingKitten.setFirstVaccination(kitten.getFirstVaccination());
                existingKitten.setSecondVaccination(kitten.getSecondVaccination());
                kittenRepository.save(existingKitten);
            } catch (Exception ex) {
                throw new DatabaseErrorException();
            }
        } else {
            throw new RecordNotFoundException();
        }
    }

    @Override
    public void updatePrice(long id, KittenRequest price) {
        if (priceRepository.existsById(id)) {
            try {
                Price existingPrice = priceRepository.findById(id).orElse(null);
                existingPrice.setBreedPrice(price.getBreedPrice());
                existingPrice.setFirstVaccinationPrice(price.getFirstVaccinationPrice());
                existingPrice.setSecondVaccinationPrice(price.getSecondVaccinationPrice());
                priceRepository.save(existingPrice);
            } catch (Exception ex) {
                throw new DatabaseErrorException();
            }
        } else {
            throw new RecordNotFoundException();
        }
    }

    @Override
    public void deleteKitten(long id) {
        kittenRepository.deleteById(id);
    }
}

共有1个答案

郎吉星
2023-03-14

关于您的代码,我在这里有很多话要说,但让我们看看这里的主要问题是什么。问题很简单,如果您查看KittenBuilder,您使用这个构建器创建了一个Kitten,但是您的Kitten构造函数是空的。

public Kitten(String name, LocalDate dateOfBirth, double weight, String breed, String firstVaccination, String secondVaccination) {
    this.name = name;
    this.dateOfBirth = dateOfBirth;
    this.weight = weight;
    this.breed = breed;
    this.firstVaccination = firstVaccination;
    this.secondVaccination = secondVaccination;
}

这将填充Kitten对象,然后您就可以开始了。

关于代码的一些建议

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
@Service
@Transactional
class KittenServiceImpl implementes ...

最好的做法之一是不要直接在控制器中使用实体,而是使用DTO(Data Transfer Object),这样您就可以将所需的属性从实体映射到DTO(这样您就可以只包含kitten属性而不使用price实体)。

最后的奖励:

public Kitten getKittenById(long id) {
    if (!kittenRepository.existsById(id)) {
       throw new RecordNotFoundException("");
    }
    return kittenRepository.findById(id).orElse(null);
}

这可以简化为:

public Kitten getKittenById(long id) {
    return kittenRepository.findById(id).orElseThrow(() -> new RecordNotFoundException());
}
 类似资料:
  • 我想使用带有mysql的npm包knex将myback-end文件夹与localhost上的mysql数据库连接起来。 步骤: 在后端项目文件夹(包含knex和mysql)中运行nodemon server.js文件 在《邮差》中,我喜欢: 打开“邮递员”,选择“Post Requst”,复制URL:localhost:3000/myPath“,复制到正文: {“电子邮件”:“me@gmail.c

  • 我正在用Thymeleaf构建一个Spring Boot应用程序。我的模板(视图)和静态文件夹都在src/main/Resources/静态和src/main/Resources/tem板下。当我通过main方法(使用eclipse)运行应用程序时,一切都很好。但是,我已经按照说明创建了一个war文件,当我将其部署到Tomcat 7时——静态内容丢失了,只显示了Thymeleaf html模板。

  • 我有一个python代码,用来创建一个json文件,作为post请求中的数据。 变量如下所示: 当我打印上述变量时,我得到以下输出: 当我在我的邮递员请求上使用以下输出时,它会像我期望的那样工作。但是当我使用相同的变量发送带有以下函数的超文本传输协议请求时,我得到了一个错误。 为什么我的输出在postman上工作,而不是在python本身?

  • 我用命令运行了一个spring boot web应用程序。但是,当将打包字段更改为war(在pom.xml中)并将其构建为war时,它未能在tomcat 7中运行。 我把我pom.xml的父母变成: 而且: 我的错误是: 我的问题是: 这里发生了什么,如何克服? 使用Spring-start真的安全吗?因为嵌入式服务器库似乎影响了它部署到j2ee容器中的可靠性。我知道,它仍然是Milestone版

  • 任何人都可以向我展示或指出一个不使用Spring引导 gradle 插件的Spring引导 gradle 项目。 我正在寻找一个类似springbootstarterwebhelloworld的例子,它不使用gradle插件。 我无法想象插件是一个需求,但搜索示例似乎都依赖于gradle插件,这在我的环境中不是一个选项,不,我也不能切换到maven。 理想情况下,gradle构建将通过添加以下内容

  • 我正在学习如何使用Docker与一个Spring Boot应用程序。我遇到了一个小障碍,我希望有人能看到这个问题。我的应用程序严重依赖于环境特定属性文件中设置的@value。在我的/src/main/resources中,我有三个属性文件 应用程序.属性 应用程序-local.properties 应用程序-prod.properties 我通常用:java-jar-dspring.profile