我尝试在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/保存}]
问题出在哪里?
1条答案
按热度按时间sr4lhrrt1#
对于您的服务类,如何声明和创建
invoiceRepository
?然后,您需要添加一个
@Autowired
:如果您有
@Autowired
,请确保您的服务类注解为@Service
:如果你有这样的代码,请确保你没有在你的控制器中创建带有
"new"
的InvoiceService
。或
"new"ing
,则使用@Autowire