I'm trying to create a post API in a spring boot app but it's not working and i can't find the issue in the code
This is service:
@Transactional
public Invoice saveInvoice(Invoice invoice) {
Invoice newInvoice = invoiceRepository.save(invoice);
return newInvoice;
}
This is the controller:
@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);
}
}
and this is the model :
@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;
}
}
But when I am running in in postman its returning 500 Internal Server Error
Update error message :
, message=Cannot invoke "com.example.invoices.repository.IInvoiceRepository.save(Object)" because "this.invoiceRepository" is null, path=/invoice/save}]
where's the problem ?
CodePudding user response:
For your service class, how are you declaring and creating invoiceRepository? If it's like this:
private InvoiceRepository invoiceRepository;
Then you need to add an @Autowired:
@Autowired
private InvoiceRepository invoiceRepository;
If you do have it @Autowired, make sure your service class is annotated with @Service:
@Service
public class InvoiceService {...}
If you have that, make sure you aren't creating InvoiceService with "new" in your controller. Instead of:
private InvoiceService invoiceService = new InvoiceService();
or "new"ing it in a constructor, use @Autowire
@Autowire
private InvoiceService invoiceService;