I am trying to create a Spring Boot program where I can save different products that a business may have for sale. I am saving the products into MongoDB.
Currently, I am trying to use PostMan to save a product into the database. However, PostMan keeps giving me this error, and I was wondering what I am doing wrong (this is the URL I am inputting into PostMan: "http://localhost:8080/mdb-spring-boot-product-organizer/api/addProduct"):
{
"timestamp": "2022-12-07T22:56:33.866+00:00",
"status": 404,
"error": "Not Found",
"path": "/mdb-spring-boot-product-organizer/api/addProduct"
}
Project Explorer
Controller Code
package com.example.mdbspringbootproductorganizer.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.mdbspringbootproductorganizer.model.Product;
import com.example.mdbspringbootproductorganizer.repository.ProductRepository;
#RestController
#RequestMapping("/api")
public class ProductController {
#Autowired
private ProductRepository repository;
#PostMapping("/addProduct")
public String saveProduct(#RequestBody Product product) {
repository.save(product);
return "Added product with id : " + product.getId();
}
#GetMapping("/findAllProducts")
public List<Product> getProducts() {
return repository.findAll();
}
#GetMapping("/findAllProducts/{id}")
public Optional<Product> getProduct(#PathVariable int id) {
return repository.findById(id);
}
#DeleteMapping("/delete/{id}")
public String deleteBook(#PathVariable int id) {
repository.deleteById(id);
return "Product deleted with id: " + id;
}
}
Repository
package com.example.mdbspringbootproductorganizer.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.example.mdbspringbootproductorganizer.model.Product;
public interface ProductRepository extends MongoRepository<Product, Integer> {
}
POJO
package com.example.mdbspringbootproductorganizer.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "ProductInventory")
public class Product {
#Id
private int id;
private String name;
private double listedPrice;
private double purchasePrice;
private String condition;
private String brand;
private char shelf;
private int bin;
public Product(int id, String name, double listedPrice, double purchasePrice, String condition, String brand,
char shelf, int bin) {
super();
this.id = id;
this.name = name;
this.listedPrice = listedPrice;
this.purchasePrice = purchasePrice;
this.condition = condition;
this.brand = brand;
this.shelf = shelf;
this.bin = bin;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getListedPrice() {
return listedPrice;
}
public void setListedPrice(double listedPrice) {
this.listedPrice = listedPrice;
}
public double getPurchasePrice() {
return purchasePrice;
}
public void setPurchasePrice(double purchasePrice) {
this.purchasePrice = purchasePrice;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public char getShelf() {
return shelf;
}
public void setShelf(char shelf) {
this.shelf = shelf;
}
public int getBin() {
return bin;
}
public void setBin(int bin) {
this.bin = bin;
}
#Override
public String toString() {
return "Product [idNumber=" + id + ", name=" + name + ", listedPrice=" + listedPrice + ", purchasePrice="
+ purchasePrice + ", condition=" + condition + ", brand=" + brand + ", shelf=" + shelf + ", bin=" + bin
+ "]";
}
}
Main class
package com.example.mdbspringbootproductorganizer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#SpringBootApplication
#EnableMongoRepositories
public class MdbSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MdbSpringBootApplication.class, args);
}
}````
I have been trying to add different annotations or rename my packages, but none of that has worked.
I don't think mdb-spring-boot-product-organizer should be part of the URL.
Try making a POST to http://localhost:8080/api/addProduct.
Try adding #ComponentScan to your Spring boot application class.
#SpringBootApplication
#EnableMongoRepositories
#ComponentScan(basePackages={"com.example.mdbspringbootproductorganizer.controller","com.example.mdbspringbootproductorganizer.repository"})
public class MdbSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MdbSpringBootApplication.class, args);
}
}
This error comes usually when your spring boot application cannot find the URL (since it is defined in different package than one with #SpringBootApplication class) despite defined in Controller!
Related
I'd like to write some java code using spring boot to consume JSON data from a specific endpoint. However with each request the response may return different data fields as such.
{"success":true,"terms":"https:\/\/coinlayer.com\/terms","privacy":"https:\/\/coinlayer.com\/privacy","timestamp":1645616586,"target":"USD","rates":{"BTC":39049.424242}}
{"success":true,"terms":"https:\/\/coinlayer.com\/terms","privacy":"https:\/\/coinlayer.com\/privacy","timestamp":1645626666,"target":"USD","rates":{"BTC":39061.184046,"ETH":2726.545731}}
{"success":true,"terms":"https:\/\/coinlayer.com\/terms","privacy":"https:\/\/coinlayer.com\/privacy","timestamp":1645626966,"target":"USD","rates":{"ADA":0.939301,"BTC":39006.990707,"ETH":2720.502765}}
and so on.
Below is my current code which deals with the first case presented. I could write another Rates.java to cater for the second case and so on but I'm looking to have one Rates.java file which deals with all possible cases.
LiveData.java
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class LiveData {
private Boolean success;
private String terms;
private String privacy;
private Long timestamp;
private String target;
private Rates rates;
public LiveData() {
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getTerms() {
return terms;
}
public void setTerms(String terms) {
this.terms = terms;
}
public String getPrivacy() {
return privacy;
}
public void setPrivacy(String privacy) {
this.privacy = privacy;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public Rates getRates() {
return rates;
}
public void setValue(Rates rates) {
this.rates = rates;
}
#Override
public String toString() {
return "LiveData{" +
"success='" + success + '\'' +
"terms='" + terms + '\'' +
"privacy='" + privacy + '\'' +
"timestamp='" + timestamp + '\'' +
"target='" + target + '\'' +
"rates=" + rates +
'}';
}
}
Rates.java
package com.example.consumingrest;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Rates {
#JsonProperty(value = "BTC")
private BigDecimal btc;
public Rates() {
}
public BigDecimal getBTC() {
return this.btc;
}
public void setId(BigDecimal btc) {
this.btc = btc;
}
#Override
public String toString() {
return "{" +
"BTC='" + btc + '\''+
'}';
}
}
ConsumingRest.java (main)
package com.example.consumingrest;
import java.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class ConsumingRestApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
#Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
LiveData liveData = restTemplate.getForObject(
"http://api.coinlayer.com/api/live?access_key=121a4df8b95fd5be872da3bad101cd73&target=EUR&symbols=BTC", LiveData.class);
log.info(liveData.toString());
};
}
}
As mentioned in the comments, seems you want a map containing the rates:
#JsonIgnoreProperties(ignoreUnknown = true)
public class LiveData {
...
private Map<String, BigDecimal> rates;
See Mapping a Dynamic JSON Object
Any Json Object can be parsed to Map<String, Object> where Object may be anything including Map or List. So, your map may be nested with any depth and it can contain Lists with any objects including maps. Any of your responses can be always parsed to that structure. So, return that structure and you won't have to worry about different formats - This is one size fits all.
I am trying to deserialize following JSON:
{
"name": "myName",
"decoder": "myDecoder",
"id": 123,
"definition": {
"AND": [
"and-condition-1",
"and-condition-2",
{
"OR": [
"or-condition-1",
"or-condition-2"
]
}
]
}
}
I have deserialized the file:
ObjectMapper mapper = new ObjectMapper();
RuleDefinition ruleDefinition = mapper.readValue(new File(fileName), RuleDefinition.class);
in to following Object-Structure:
RuleDefinition.java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class RuleDefinition {
#JsonProperty("name")
private String name;
#JsonProperty("decoder")
private String decoder;
#JsonProperty("id")
private int id;
#JsonProperty("definition")
private Definition definition;
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("decoder")
public String getDecoder() {
return decoder;
}
#JsonProperty("decoder")
public void setDecoder(String decoder) {
this.decoder = decoder;
}
#JsonProperty("id")
public int getId() {
return id;
}
#JsonProperty("id")
public void setId(int id) {
this.id = id;
}
#JsonProperty("definition")
public Definition getDefinition() {
return definition;
}
#JsonProperty("definition")
public void setDefinition(Definition definition) {
this.definition = definition;
}
#Override
public String toString() {
return "RuleDefinition{" +
"name='" + name + '\'' +
", decoder='" + decoder + '\'' +
", id=" + id +
", definition=" + definition +
'}';
}
}
Definition.Java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Definition {
#JsonProperty("AND")
private List<AND> AND;
public List<AND> getAND() {
return AND;
}
public void setAND(List<AND> AND) {
this.AND = AND;
}
#Override
public String toString() {
return "Definition{" +
"AND=" + AND +
'}';
}
}
AND.java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class AND {
#JsonProperty("OR")
private List<String> Or;
#JsonProperty("OR")
public List<String> getOR() {
return Or;
}
#JsonProperty("OR")
public void setOR(List<String> Or) {
this.Or = Or;
}
#Override
public String toString() {
return "AND{" +
"Or=" + Or +
'}';
}
}
and i got the following error
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.model.AND: no String-argument constructor/factory method to deserialize from String value ('and-condition-1')
I see that the issue is because of 'and-condition-1' which is just a value, how do I deserialize these, I wanted to know should I write a custom deserializer (or) Is there any work around?
I think the problem is that in your JSON the AND object is both a string and an object. You should create a JsonDeserializer for it.
enter link description here
enter link description here
I'm learning Java EE Development with the book Java EE7 Development with Wildfly. Now I encounter the Problem, if I want to run the example code I get the error:
EJB Invocation failed on component TheatreBox for method public void de.wflydevelopment.chapter4.boundary.TheatreBox.buyTicket(int): javax.ejb.EJBTransactionRolledbackException
Until now I can't fix the Problem and I have no idead what could cause this error. I already compared the example Code with mine, but no luck.
AutomaticSellerService
package de.wflydevelopment.chapter4.control;
import java.util.Collection;
import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.inject.Inject;
import org.jboss.logging.Logger;
import de.wflydevelopment.chapter4.boundary.TheatreBox;
import de.wflydevelopment.chapter4.entity.Seat;
#Stateless
public class AutomaticSellerService {
#Inject
private Logger logger;
#Inject
private TheatreBox theatreBox;
#Resource
private TimerService timerService;
#Schedule(hour = "*", minute = "*", second = "*/30", persistent = false)
public void automaticCustomer() {
final Seat seat = findFreeSeat();
if(seat == null) {
cancelTimers();
logger.info("Scheduler gone!");
return;
}
theatreBox.buyTicket(seat.getId()); //I think this line causes the error
logger.info("Somebody just booked seat number " + seat.getId());
}
private Seat findFreeSeat(){
final Collection<Seat> list = theatreBox.getSeats();
for(Seat seat : list) {
if(!seat.isBooked()) {
return seat;
}
}
return null;
}
private void cancelTimers() {
for(Timer timer : timerService.getTimers()) {
timer.cancel();
}
}
}
TheatreBox
package de.wflydevelopment.chapter4.boundary;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.ejb.AccessTimeout;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import org.jboss.logging.Logger;
import de.wflydevelopment.chapter4.entity.Seat;
#Singleton
#Startup
#AccessTimeout(value = 5, unit = TimeUnit.MINUTES)
public class TheatreBox {
#Inject
private Logger logger;
private Map<Integer, Seat> seats;
#Inject
private Event<Seat> seatEvent;
#PostConstruct
public void setupTheatre() {
seats = new HashMap<>();
int id = 0;
for (int i = 0; i < 5; i++) {
addSeat(new Seat(++id, "Stalls", 40));
addSeat(new Seat(++id, "Circle", 20));
addSeat(new Seat(++id, "Balcony", 10));
}
logger.info("Seat Map constructed.");
}
private void addSeat(Seat seat) {
seats.put(seat.getId(), seat);
}
#Lock(LockType.READ)
public Collection<Seat> getSeats() {
return Collections.unmodifiableCollection(seats.values());
}
#Lock(LockType.READ)
public int getSeatPrice(int seatId) {
return getSeat(seatId).getPrice();
}
#Lock(LockType.WRITE)
public void buyTicket(int seatId) {
final Seat seat = getSeat(seatId);
final Seat bookedSeat = seat.getBookedSeat();
addSeat(bookedSeat);
seatEvent.fire(bookedSeat);
}
#Lock()
private Seat getSeat(int seatId) {
final Seat seat = seats.get(seatId);
return seat;
}
}
EDIT 1
In findFreeSeat() I'm able to use theatreBox but when I try to use theatreBox.buyTicket(seat.getId()); my application crashes. Removing this line also removes the error.
EDIT 2
seatEvent.fire(bookedSeat); causes the problem inside theatreBox.buyTicket(seat.getId())
EDIT 3
package de.wflydevelopment.chapter4.controller;
import java.io.Serializable;
import javax.enterprise.event.Observes;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import de.wflydevelopment.chapter4.entity.Seat;
#Named
#ViewScoped
public class BookingRecord implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int bookedCount = 0;
public int getBookedCount() {
return bookedCount;
}
public void bookEvent(#Observes Seat bookedSeat) {
bookedCount++;
}
}
EDIT 4
Seat.java
package de.wflydevelopment.chapter4.entity;
public class Seat{
private final int id;
private final String name;
private final int price;
private final boolean booked;
public Seat(int id, String name, int price) {
this(id, name, price, false);
}
private Seat(int id, String name, int price, boolean booked) {
this.id = id;
this.name = name;
this.price = price;
this.booked = booked;
}
public Seat getBookedSeat() {
return new Seat(getId(), getName(), getPrice(), true);
}
public int getId() {
return id;
}
public boolean isBooked() {
return booked;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
#Override
public String toString() {
return "Seat [id=" + id + ", name=" + name + ", price=" + price + ", booked=" + booked + "]";
}
}
I was following the start-up guide of at spring website https://spring.io/guides/gs/consuming-rest/.
I am not following the exact tutorial in the sense that I am using another endpoint: http://www.omdbapi.com?s=rush.
I am having an issue with JSON conversion to POJO. I am not getting any error or exceptions. Could someone point out where am I going wrong?
You can find the complete code here
Here are my POJOs:
package com.sample.restapi.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class SearchResponse {
private List<Search> search;
private String totalResults;
private String response;
public SearchResponse() {
}
public List<Search> getSearch() {
return search;
}
public void setSearch(List<Search> search) {
this.search = search;
}
public String getTotalResults() {
return totalResults;
}
public void setTotalResults(String totalResults) {
this.totalResults = totalResults;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
#Override
public String toString() {
return "SearchResponse [search=" + search + ", totalResults=" + totalResults + ", response=" + response + "]";
}
}
Here is the Search.java
package com.sample.restapi.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown=true)
public class Search {
private String title;
private String year;
private String imdbID;
private String type;
private String poster;
public Search() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getImdbID() {
return imdbID;
}
public void setImdbID(String imdbID) {
this.imdbID = imdbID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
#Override
public String toString() {
return "Search [title=" + title + ", year=" + year + ", imdbID=" + imdbID + ", type=" + type + ", poster="
+ poster + "]";
}
}
Here is the driver class.
package com.sample.restapi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;
import com.sample.restapi.model.SearchResponse;
#SpringBootApplication
public class ConsumerApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumerApplication.class);
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
SearchResponse searchResponse = restTemplate.getForObject("http://www.omdbapi.com?s=rush", SearchResponse.class);
log.info(searchResponse.toString());
}
}
The console output is :
14:34:12.941 [main] INFO com.sample.restapi.ConsumerApplication - SearchResponse [search=null, totalResults=344, response=null]
You are missing correct identifiers for the properties in the json, there are differences in the response and your classes in the Capital and lower case letters. Use #JsonProperty in your classes.
#JsonProperty("Search")
private List<Search> search = new ArrayList<Search>();
private String totalResults;
#JsonProperty("Response")
private String response;
you should also add #JsonProperty annotations in the Search class.
I am newbie to spring and java,
I have a case, where i am trying to fetching rows from the mysql table
This is my Controller:
#RequestMapping(value = "/pharmacy/order/dates", method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public PharmacyOrderDateResponse orderDates(#Valid #RequestBody PharmacyOrderDateRequest request) {
List<PrescriptionOrder> pharmacyOrders = prescriptionOrderService.orderDatesByPharmacyId(request.getPharmacyId(), request.getOrderStatus(), true);
if(pharmacyOrders.size() == 0) {
throw new EntityNotFoundException("No pharmacy orders found");
}
PharmacyOrderDateResponse response = new PharmacyOrderDateResponse();
Set<Date> orderDateSet = new HashSet<>();
for(PrescriptionOrder pharmacyOrder : pharmacyOrders) {
//orderDateSet.add(longToDate(pharmacyOrder.getCreatedAt().getTime()));
}
response.setPharmacyId(pharmacyOrders.get(0).getPharmacyId());
response.setStatus(ResponseStatusCode.SUCCESS);
response.setPharmacyOrderDateDetails(orderDateSet);
response.setTotalDates(orderDateSet.size());
return response;
}
The above controller is used to call the service by the function, so that to get the list of prescription orders.
This is my Service:
package com.axonytes.corporate.service;
import java.util.Date;
import java.util.List;
import com.axonytes.corporate.entity.PrescriptionOrder;
public interface PrescriptionOrderService {
List<PrescriptionOrder> orderDatesByPharmacyId(Long labId, String orderStatus, Boolean status);
}
This is my ServiceImpl:
#Service
#Transactional(readOnly = true)
public class PrescriptionOrderServiceImpl implements PrescriptionOrderService {
private PrescriptionOrderRepository prescriptionOrderRepository;
#Autowired
public PrescriptionOrderServiceImpl(PrescriptionOrderRepository prescriptionOrderRepository) {
this.prescriptionOrderRepository = prescriptionOrderRepository;
}
#Override
public List<PrescriptionOrder> orderDatesByPharmacyId(Long pharmacyId, String orderStatus, Boolean status) {
OrderStatusEnum orderStatusEnum = OrderStatusEnum.fromString(orderStatus);
List<PrescriptionOrder> prescriptionOrder = prescriptionOrderRepository
.findByPharmacyIdAndOrderStatus(pharmacyId, orderStatusEnum.getStatus());
return prescriptionOrder;
}
}
The above service is a implementation function to list the orders, where it calls the repository function.
This is my Repository:
package com.axonytes.corporate.repository;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.axonytes.corporate.entity.PrescriptionOrder;
#Repository
public interface PrescriptionOrderRepository extends JpaRepository<PrescriptionOrder, Long>{
//#Query(value = "select * from PrescriptionOrder po WHERE po.pharmacyId = :pharmacyId AND po.orderStatus = :orderStatus AND po.active = :active ORDER BY po.createdAt ASC")
//List<PrescriptionOrder> findByPharmacyIdAndOrderStatus(#Param("pharmacyId") Long pharmacyId, #Param("orderStatus") int orderStatus, #Param("active") Boolean active);
List<PrescriptionOrder> findByPharmacyIdAndOrderStatus(#Param("pharmacyId") Long pharmacyId, #Param("orderStatus") int orderStatus);
}
This is my Entity:
package com.axonytes.corporate.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
#Entity
#DynamicInsert
#DynamicUpdate
#Table(name = "prescription_orders")
public class PrescriptionOrder extends BaseEntity {
private static final long serialVersionUID = -3853355500806579362L;
#Column(name = "prescription_id")
private Long prescriptionId;
#Column(name = "pharmacy_id")
private Long pharmacyId;
#Column(name = "order_status")
private int orderStatus;
public Long getPrescriptionId() {
return prescriptionId;
}
public void setPrescriptionId(Long prescriptionId) {
this.prescriptionId = prescriptionId;
}
public Long getPharmacyId() {
return pharmacyId;
}
public void setPharmacyId(Long pharmacyId) {
this.pharmacyId = pharmacyId;
}
public int getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(int orderStatus) {
this.orderStatus = orderStatus;
}
}
This ismy OrderStatusEnumClass:
package com.axonytes.corporate.util;
public enum OrderStatusEnum {
PENDING(0, "pending"), DESPATCHED(1, "dispatched");
private int status;
private String name;
OrderStatusEnum(int status, String name) {
this.status = status;
this.name = name;
}
public static OrderStatusEnum fromString(String name) {
if(name != null) {
for(OrderStatusEnum orderStatusEnum : OrderStatusEnum.values()) {
if(name.equalsIgnoreCase(orderStatusEnum.toString())) {
return orderStatusEnum;
}
}
}
return null;
}
#Override
public String toString() {
return name;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
I have row values in the mysql:
id prescription_id pharmacy_id order_Status is_active
1 1 6 0 1
I am trying to list a orders by the following api.
http://localhost:8080/pharmacy/order/dates
POST METHOD with JSON VALUE:
{
"pharmacyId":"6",
"orderStatus":"pending"
}
Eventhough i am having 1 rows in the mysql db table, Output i am getting is:
{
"status": "FAILURE",
"errorCode": 0,
"errorMessage": "No pharmacy orders found"
}
Here you are using spring data and name method resolving. So is spring who translate the name of your method with each property in your entity, in that case you don't have to declare any parameter name so change your method to this:
#Repository
public interface PrescriptionOrderRepository extends JpaRepository<PrescriptionOrder, Long>{
List<PrescriptionOrder> findByPharmacyIdAndOrderStatus(Long pharmacyId, int orderStatus);
}
Note: You have an enum OrderStatusEnum but you are saving into the database an integer, I highly recommend you to modify the object to store and change the int for the enum, would be easier to read