postman 500 Sping Boot 后API中的内部服务器错误

3gtaxfhh  于 2022-11-07  发布在  Postman
关注(0)|答案(1)|浏览(157)

我尝试在Sping Boot 应用程序中创建post API,但它不起作用,并且我无法在代码中找到问题
这是服务

@Transactional
    public Invoice saveInvoice(Invoice invoice) {
        Invoice newInvoice = invoiceRepository.save(invoice);
        return newInvoice;
    }

这是控制器

@PostMapping("/save")
public ResponseEntity<Invoice> addInvoice(@RequestBody InvoiceDTO invoice) {
    try {
        Invoice newInvoice = invoiceService
                .saveInvoice(new Invoice(invoice.getSerialNumber(), invoice.getStatus(), invoice.getCreatedDate()));
        return new ResponseEntity<>(newInvoice, HttpStatus.CREATED);
    } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

这是一个“模型"

@Entity
@Table(name = "invoice")
public class Invoice {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;
    @Column(name = "serial_number")
    private long serialNumber;
    @Column(name = "status")
    private String status;
    @Column(name = "created_date")
    private Timestamp createdDate;
    @Column(name = "is_deleted")
    private boolean isDeleted;

    @ManyToOne
    @JoinColumn(name = "customer_id")
    private Customer customer;

    @ManyToOne
    @JoinColumn(name = "employee_id")
    private Employee employee;

    @OneToMany
    private Set<InvoiceHistory> invoiceHistories;

    @ManyToMany
    private Set<Item> items;

    public Invoice(long serialNumber, String status, Timestamp createdDate) {
        this.serialNumber = serialNumber;
        this.status = status;
        this.createdDate = createdDate;
        this.isDeleted = false;
    }
}

但当我运行在 Postman 它返回500内部服务器错误
更新错误消息:
,消息=无法调用“com.example.invoices.repository.IInvoiceRepository.save(对象)”,因为“this.invoiceRepository”为空,路径=/invoice/保存}]
问题出在哪里?

sr4lhrrt

sr4lhrrt1#

对于您的服务类,如何声明和创建invoiceRepository

private InvoiceRepository invoiceRepository;

然后,您需要添加一个@Autowired

@Autowired
private InvoiceRepository invoiceRepository;

如果您有@Autowired,请确保您的服务类注解为@Service

@Service
public class InvoiceService {...}

如果你有这样的代码,请确保你没有在你的控制器中创建带有"new"InvoiceService

private InvoiceService invoiceService = new InvoiceService();

"new"ing,则使用@Autowire

@Autowire
private InvoiceService invoiceService;

相关问题