I am using spring boot as a backend rest API and connecting to a MySQL database. I created the initial entity and database table that it would map to. I realized one of the columns in my database was named incorrectly and updated its name in the database and updated my entity to reflect the change as well. After doing so, when I send a GET or POST request to my controller endpoints, the values of the returned object do not reflect the changes I made to the entity/database. I have tried changing the spring.jpa.hibernate.ddl-auto property in my applications.properties file to update, create, and create drop, none of which had any success. Here is my entity class, applications.properties file, my controller endpoints, my repository, and 2 images, one of my database table and one of the response from the GET endpoint.
Skin.java
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#Entity
#Table(name="skins")
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Skin {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Column(name="category")
private String category;
#Column(name="collection")
private String collection;
#Column(name="quality")
private String quality;
#Column(name="wear")
private String wear;
#Column(name="weapon")
private String weapon;
#Column(name="name")
private String name;
#Column(name="price")
private BigDecimal price;
#Column(name="quantity")
private int quantity;
#Column(name="date_bought")
private Date dateBought;
#ManyToOne(cascade= {CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH})
#JoinColumn(name="trade_id")
private Trade trade;
#Column(name="outcome_sell_price")
private BigDecimal outcomeSellPrice;
#Column(name="date_traded")
private Date dateTraded;
#Column(name="sell_price")
private BigDecimal sellPrice;
#Column(name="date_sold")
private Date dateSold;
public Skin() {
}
public Skin(String category, String collection, String quality, String wear, String weapon, String name,
BigDecimal price, int quantity, Date dateBought, Trade trade, BigDecimal outcomeSellPrice, Date dateTraded,
BigDecimal sellPrice, Date dateSold) {
this.category = category;
this.collection = collection;
this.quality = quality;
this.wear = wear;
this.weapon = weapon;
this.name = name;
this.price = price;
this.quantity = quantity;
this.dateBought = dateBought;
this.trade = trade;
this.outcomeSellPrice = outcomeSellPrice;
this.dateTraded = dateTraded;
this.sellPrice = sellPrice;
this.dateSold = dateSold;
}
public String getWeapon() {
return weapon;
}
public void setWeapon(String weapon) {
this.weapon = weapon;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCollection() {
return collection;
}
public void setCollection(String collection) {
this.collection = collection;
}
public String getWear() {
return wear;
}
public void setWear(String wear) {
this.wear = wear;
}
public String getQuality() {
return quality;
}
public void setQuality(String quality) {
this.quality = quality;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Date getDateBought() {
return dateBought;
}
public void setDateBought(Date dateBought) {
this.dateBought = dateBought;
}
public Trade getTrade() {
return trade;
}
public void setTrade(Trade trade) {
this.trade = trade;
}
public BigDecimal getSellPrice() {
return sellPrice;
}
public void setSellPrice(BigDecimal sellPrice) {
this.sellPrice = sellPrice;
}
public Date getDateTraded() {
return dateTraded;
}
public void setDateTraded(Date dateTraded) {
this.dateTraded = dateTraded;
}
public BigDecimal getSoldAt() {
return outcomeSellPrice;
}
public void setSoldAt(BigDecimal soldAt) {
this.outcomeSellPrice = soldAt;
}
public Date getDateSold() {
return dateSold;
}
public void setDateSold(Date dateSold) {
this.dateSold = dateSold;
}
#Override
public String toString() {
return "Skin [id=" + id + ", category=" + category + ", collection=" + collection + ", quality=" + quality
+ ", wear=" + wear + ", weapon=" + weapon + ", name=" + name + ", price=" + price + ", quantity="
+ quantity + ", dateBought=" + dateBought + ", trade=" + trade + ", outcomeSellPrice=" + outcomeSellPrice
+ ", dateTraded=" + dateTraded + ", sellPrice=" + sellPrice + ", dateSold=" + dateSold + "]";
}
}
Controller Endpoints
#Autowired
SkinRepository sr;
#GetMapping("")
public List<Skin> getSkins() {
return sr.findByTradeIdNullAndDateSoldNull();
}
#PostMapping("")
public Skin insertSkin(#RequestBody Skin skin) {
// need to figure out why this isn't picking up the database changes
return sr.save(skin);
}
SkinRepository.java
#Repository
public interface SkinRepository extends JpaRepository<Skin, Long> {
List<Skin> findByTradeIdNullAndDateSoldNull();
}
application.properties
spring.datasource.url=jdbc:mysql://${DB_HOST}:${DB_PORT}/${DB_SCHEMA}?useSSL=false&serverTimezone=UTC
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASS}
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
spring.jpa.hibernate.ddl-auto=update
Database Table
This is the response I get when sending a request to the GET endpoint. The value soldAt is the old name of the column before changing it, it should be outcome_sell_price.
GET endpoint response
Any thoughts on how I can get the response from the endpoints to match the database and entity would be greatly appreciated. Thanks in advance.
The reason why you still get soldAt related names might be because you have the following getter and setters. Remove or update this getter and setters too and see if you still get erroneous responses.
public BigDecimal getSoldAt() {
return outcomeSellPrice;
}
public void setSoldAt(BigDecimal soldAt) {
this.outcomeSellPrice = soldAt;
}
Related
I have multiple Entities mapped to my MySQL database and I can map those entities into relevant objects using Spring's CrudRepository. The three entities are: Snapshot, Market, and Contract
Each Snapshot contains a unique id, a timestamp, and a List of Market objects
Each Market contains a unique primary key id, a nonUniquemarketId, name, url, ...., and List of Contract objects.
Each Contract contains fields regarding pricing information.
The nonUniqueMarketId is an id given by the API I am getting data from. It only occurs once in each Snapshot's List of Market objects
I am wondering if it is possible to get the List of Contracts from a specific Market in List of Markets from a specific Snapshot. That is, if I have a Snapshot's timestamp and a nonUniqueMarketId, is it possible to write a query that looks at all the Snapshots in the DB, gets the one with the given timestamp, then looks at that Snapshot's List of Markets and either gets that Market whose nonUniqueMarketId is given or the List of Contracts field in it?
More generally, I know what Snapshot I want and what Market I want, is it possible to get that specific Market given those two parameters?
Snapshot.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.List;
#Entity
public class Snapshot{
#Id
private Integer hashId;
#JsonProperty("markets")
#ElementCollection(fetch=FetchType.EAGER)
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) //ALL, not persist
private List<Market> markets;
private long timestamp;
public Snapshot(List<Market> markets, long timestamp, Integer hashId) {
this.markets = markets;
this.timestamp = timestamp;
this.hashId = hashId;
}
public Snapshot() {
}
public void setMarkets(List<Market> markets){
this.markets = markets;
}
public List<Market> getMarkets(){
return markets;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public Integer getHashId() {
return hashId;
}
public void setHashId(Integer hashId) {
this.hashId = hashId;
}
#Override
public String toString() {
return "Snapshot{" +
"hashId=" + hashId +
", markets=" + markets +
", timestamp=" + timestamp +
'}';
}
}
Market.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.List;
#Entity
public class Market {
#Id
#GeneratedValue
private Integer marketUniqueID;
#JsonProperty("timeStamp")
private String timeStamp;
#Transient
#JsonProperty("image")
private String image;
#JsonProperty("name")
private String name;
#JsonProperty("id")
private int id;
#Transient
#JsonProperty("shortName")
private String shortName;
#ElementCollection(fetch=FetchType.EAGER)
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) //ALL, not persist
#JsonProperty("contracts")
private List<Contract> contracts;
#JsonProperty("url")
private String url;
#JsonProperty("status")
private String status;
public Market(String timeStamp, String image, String name, int id, String shortName, List<Contract> contracts, String url, String status) {
this.timeStamp = timeStamp;
this.image = image;
this.name = name;
this.id = id;
this.shortName = shortName;
this.contracts = contracts;
this.url = url;
this.status = status;
}
public Market() {
}
public Integer getMarketUniqueID() {
return marketUniqueID;
}
public void setMarketUniqueID(Integer marketUniqueID) {
this.marketUniqueID = marketUniqueID;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public List<Contract> getContracts() {
return contracts;
}
public void setContracts(List<Contract> contracts) {
this.contracts = contracts;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "\n\nMarket{" +
"marketUniqueID='" + marketUniqueID + '\'' +
", timeStamp='" + timeStamp + '\'' +
", image='" + image + '\'' +
", name='" + name + '\'' +
", id=" + id +
", shortName='" + shortName + '\'' +
", contracts=" + contracts +
", url='" + url + '\'' +
", status='" + status + '\'' +
"\n}";
}
}
Contract.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;
#Entity
public class Contract {
/*
Why do we need contractUniqueID?:
See explanation in Market.java
Basically, the JsonProperty 'id' field cannot be used as a primary key in the database. We need to create one, so we generate it here.
*/
#Id
#GeneratedValue
private Integer contractUniqueID;
#Transient
#JsonProperty("image")
private String image;
#JsonProperty("lastClosePrice")
private double lastClosePrice;
#JsonProperty("bestBuyNoCost")
private double bestBuyNoCost;
#JsonProperty("bestSellNoCost")
private double bestSellNoCost;
#Transient
#JsonProperty("displayOrder")
private int displayOrder; //not sure what this even is supposed to do lol
#JsonProperty("dateEnd")
private String dateEnd;
#JsonProperty("bestSellYesCost")
private double bestSellYesCost;
#JsonProperty("bestBuyYesCost")
private double bestBuyYesCost;
#JsonProperty("lastTradePrice")
private double lastTradePrice;
#JsonProperty("name")
private String name;
#JsonProperty("id")
private int id;
#Transient
#JsonProperty("shortName")
private String shortName;
#JsonProperty("status")
private String status;
public Contract(String image, double lastClosePrice, double bestBuyNoCost, double bestSellNoCost, int displayOrder, String dateEnd, double bestSellYesCost, double bestBuyYesCost, double lastTradePrice, String name, int id, String shortName, String status) {
this.image = image;
this.lastClosePrice = lastClosePrice;
this.bestBuyNoCost = bestBuyNoCost;
this.bestSellNoCost = bestSellNoCost;
this.displayOrder = displayOrder;
this.dateEnd = dateEnd;
this.bestSellYesCost = bestSellYesCost;
this.bestBuyYesCost = bestBuyYesCost;
this.lastTradePrice = lastTradePrice;
this.name = name;
this.id = id;
this.shortName = shortName;
this.status = status;
}
public Contract() {
}
public Integer getContractUniqueID() {
return contractUniqueID;
}
public void setContractUniqueID(Integer contractUniqueID) {
this.contractUniqueID = contractUniqueID;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public double getLastClosePrice() {
return lastClosePrice;
}
public void setLastClosePrice(double lastClosePrice) {
this.lastClosePrice = lastClosePrice;
}
public double getBestBuyNoCost() {
return bestBuyNoCost;
}
public void setBestBuyNoCost(double bestBuyNoCost) {
this.bestBuyNoCost = bestBuyNoCost;
}
public double getBestSellNoCost() {
return bestSellNoCost;
}
public void setBestSellNoCost(double bestSellNoCost) {
this.bestSellNoCost = bestSellNoCost;
}
public int getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(int displayOrder) {
this.displayOrder = displayOrder;
}
public String getDateEnd() {
return dateEnd;
}
public void setDateEnd(String dateEnd) {
this.dateEnd = dateEnd;
}
public double getBestSellYesCost() {
return bestSellYesCost;
}
public void setBestSellYesCost(double bestSellYesCost) {
this.bestSellYesCost = bestSellYesCost;
}
public double getBestBuyYesCost() {
return bestBuyYesCost;
}
public void setBestBuyYesCost(double bestBuyYesCost) {
this.bestBuyYesCost = bestBuyYesCost;
}
public double getLastTradePrice() {
return lastTradePrice;
}
public void setLastTradePrice(double lastTradePrice) {
this.lastTradePrice = lastTradePrice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "Contract{" +
"contractUniqueID='" + contractUniqueID + '\'' +
", image='" + image + '\'' +
", lastClosePrice=" + lastClosePrice +
", bestBuyNoCost=" + bestBuyNoCost +
", bestSellNoCost=" + bestSellNoCost +
", displayOrder=" + displayOrder +
", dateEnd='" + dateEnd + '\'' +
", bestSellYesCost=" + bestSellYesCost +
", bestBuyYesCost=" + bestBuyYesCost +
", lastTradePrice=" + lastTradePrice +
", name='" + name + '\'' +
", id=" + id +
", shortName='" + shortName + '\'' +
", status='" + status + '\'' +
'}';
}
}
I have two table Parent table is Credit in that table only one row of data is there and another one is child table Debit that contains multiple row of data. how to fetch data from two table which has to match id of parent class and child class and no duplicate is shown from parent class.
I have try with (from Credit,debit) but that can display with duplicate and not properly data is shown based on id.
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}
}
1.CreditDaoImpl.java
package com.rojmat.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.rojmat.dao.CreditDao;
import com.rojmat.entity.Credit;
#Repository
public class CreditDaoImpl implements CreditDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addCreditDebit(Credit credit) {
try {
sessionFactory.getCurrentSession().saveOrUpdate(credit);
} catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void deleteCreditDebit(int cid) {
/*Credit credit = (Credit)sessionFactory.getCurrentSession().createQuery("from Credit as c LEFT JOIN FETCH c.Debit where c.cid="+cid).uniqueResult();
List<Debit> debits = credit.getDebit();
sessionFactory.getCurrentSession().delete(credit);
debits.forEach((debit) -> {
sessionFactory.getCurrentSession().delete(debit);
});*/
}
#SuppressWarnings("unchecked")
#Override
public List<Credit> getAllCreditDebit() {
List<Credit> credit = sessionFactory.getCurrentSession().createQuery("from Credit,Debit").list();
return credit;
}
}
try this example: you put "distinct" before the property you do not want to be duplicated
//SQL query
select distinct credit.idCredit as idCredit from Credit credit Left Join Debit debit on credit.idCredit= debit.idCredit
//HQL query
#Entity(name = "Credit")
#Table(name = "Credit")
public class Credit{
//if you put #Id --> HQL Query "select credit from Credit credit"
#Column(name = "idCredit")
private Long idCredit;
#Column(name = "label")
private String label;
#OneToMany
#JoinColumns({#JoinColumn(name = "idCredit" ,referencedColumnName = "idCredit")})
List<Debit> debits;
...
}
public class Debit{
....
#Column(name = "idCredit")
private Long idCredit;
...
}
Query query = getSession().createQuery("select distinct credit.idCredit as idCredit, credit.label as label, credit.debits as debits from Credit credit ");
query.setResultTransformer(Transformers.aliasToBean(Credit.class));
return query.list();
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/*#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}*/
}
I wrote a Query in my ProductRepository as below
#Query(value = "select p from Product p where p.code = :code")
Product findByCode(#Param("code")String code);
it's obviously that I just want the query return 1 Product, but some how when I call the API it always return a list of all my products.
this is the generated query I get from the log
Hibernate: select product0_.code as code1_4_, product0_.name as name2_4_, product0_.price as price3_4_, product0_.unit as unit4_4_ from product product0_
I cannot see the WHERE condition clause that I wrote
This is my Product class:
package com.example.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
#Entity
public class Product {
#Id
private String code;
private String name;
private Float price;
private String unit;
#JsonIgnore
#OneToMany(fetch = FetchType.LAZY, mappedBy = "product", cascade
=CascadeType.ALL)
private List<OrderLine> orderLines;
public Product(String code, String name, float price, String unit) {
this.code = code;
this.name = name;
this.price = price;
this.unit = unit;
}
public Product(String code, float price, String unit) {
this.code = code;
this.price = price;
this.unit = unit;
}
public Product(String code) {
this.code = code;
this.price = Float.valueOf(0);
}
public Product(String code, String unit) {
this.code = code;
this.unit = unit;
this.price = Float.valueOf(0);
}
public Product() {}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
#Override
public String toString() {
return "Product{" +
"code='" + code + '\'' +
", name='" + name + '\'' +
", price=" + price +
", unit='" + unit + '\'' +
'}';
}
public List<OrderLine> getOrderLines() {
return orderLines;
}
public void setOrderLines(List<OrderLine> orderLines) {
this.orderLines = orderLines;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Product)) return false;
Product product = (Product) o;
return this.getCode().equals(product.getCode());
}
#Override
public int hashCode() {
return Objects.hash(getCode());
}}
My controller
#RestController
#RequestMapping("/products")
public class ProductController {
#Autowired
ProductRepo productRepo;
#Autowired
StaffRepo staffRepo;
#Autowired
InventoryRepo inventoryRepo;
#GetMapping("/get")
public ResponseEntity getAll(){
List<Product> products = productRepo.findAll();
if(products== null){
return ResponseEntity.status(404).body("Product not found !");
}
return ResponseEntity.ok().body(products);
}
#GetMapping("/get/{code}")
public ResponseEntity getProductByCode(#PathVariable String code){
Product p = productRepo.findByCode(code);
if(p== null){
return ResponseEntity.status(404).body("Product not found !");
}
return ResponseEntity.ok().body(p);
}
I am trying to map the pojo class to my mysql database, but i always get an error when i want to get users:
java.sql.SQLSyntaxErrorException: Unknown column 'user0_.Report_id' in 'field list'
This is how the database looks like this:
database
And these are the pojo classes:
Order
package com.latinon.reportator.model;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* #author sistemas
*
*/
#Entity
#Table(name="Order")
public class Order {
private Integer id;
private Date startDate;
private Date endDate;
private BigInteger imperssions;
private String zone;
private int monetization;
private String adUnit;
private String unit;
private String adFormat;
private Double totalAmount;
private Integer platform;
private Double value;
private String valueMesure;
private Set<Device> orderDevices = new HashSet<Device>(0);
private Set<Product> orderProducts = new HashSet<Product>(0);
private Set<Report> orderReport = new HashSet<Report>(0);
private Set<User> orderUsers = new HashSet<User>(0);
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="Order_id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Temporal(TemporalType.DATE)
#Column(name="Order_start_date", nullable=false)
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
#Temporal(TemporalType.DATE)
#Column(name="Order_end_date")
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
#Column(name="Order_impressions", nullable=false)
public BigInteger getImperssions() {
return imperssions;
}
public void setImperssions(BigInteger imperssions) {
this.imperssions = imperssions;
}
#Column(name="Order_zone")
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
#Column(name="Order_monetization",nullable=false)
public int getMonetization() {
return monetization;
}
public void setMonetization(int monetization) {
this.monetization = monetization;
}
#Column(name="Order_ad_unit")
public String getAdUnit() {
return adUnit;
}
public void setAdUnit(String adUnit) {
this.adUnit = adUnit;
}
#Column(name="Order_unit",nullable=false)
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
#Column(name="Order_ad_format", nullable=false)
public String getAdFormat() {
return adFormat;
}
public void setAdFormat(String adFormat) {
this.adFormat = adFormat;
}
#Column(name="Order_total_amount", nullable=false)
public Double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(Double totalAmount) {
this.totalAmount = totalAmount;
}
#Column(name="Order_platform", nullable=false)
public Integer getPlatform() {
return platform;
}
public void setPlatform(Integer platform) {
this.platform = platform;
}
#Column(name="Order_value", nullable=false)
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
#Column(name="Order_value_mesure",nullable=false)
public String getValueMesure() {
return valueMesure;
}
public void setValueMesure(String valueMesure) {
this.valueMesure = valueMesure;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="Order_Device", joinColumns={
#JoinColumn(name="Order_Device_Order_id")
})
public Set<Device> getOrderDevices() {
return orderDevices;
}
public void setOrderDevices(Set<Device> orderDevices) {
this.orderDevices = orderDevices;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="Order_Product", joinColumns={
#JoinColumn(name="Order_Product_Order_id")
})
public Set<Product> getOrderProducts() {
return orderProducts;
}
public void setOrderProducts(Set<Product> orderProducts) {
this.orderProducts = orderProducts;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "orderId")
public Set<Report> getOrderReport() {
return orderReport;
}
public void setOrderReport(Set<Report> orderReport) {
this.orderReport = orderReport;
}
#ManyToMany(fetch=FetchType.LAZY, mappedBy="userOrders")
public Set<User> getOrderUsers() {
return orderUsers;
}
public void setOrderUsers(Set<User> orderUsers) {
this.orderUsers = orderUsers;
}
#Override
public String toString() {
return "Order [id=" + id + ", startDate=" + startDate + ", endDate=" + endDate + ", imperssions=" + imperssions
+ ", zone=" + zone + ", monetization=" + monetization + ", adUnit=" + adUnit + ", unit=" + unit
+ ", adFormat=" + adFormat + ", totalAmount=" + totalAmount + ", platform=" + platform + ", value="
+ value + ", valueMesure=" + valueMesure + "]";
}
}
Report pojo:
package com.latinon.reportator.model;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.*;
/**
* #author sistemas
*
*/
#Entity
#Table(name="User")
public class Report {
private Integer id;
private BigInteger impressions;
private Date date;
private Double grossRevenue;
private Double latinonRevenue;
private Double userRevenue;
private Double fillRate;
private BigInteger completion25;
private BigInteger completion50;
private BigInteger completion75;
private BigInteger completion100;
private BigInteger requests;
private String zone;
private Double cpm;
private Order orderId;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="Report_id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="Report_impressions")
public BigInteger getImpressions() {
return impressions;
}
public void setImpressions(BigInteger impressions) {
this.impressions = impressions;
}
#Temporal(TemporalType.DATE)
#Column(name="Report_date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Column(name="Report_gross_revenue")
public Double getGrossRevenue() {
return grossRevenue;
}
public void setGrossRevenue(Double grossRevenue) {
this.grossRevenue = grossRevenue;
}
#Column(name="Report_latinon_revenue")
public Double getLatinonRevenue() {
return latinonRevenue;
}
public void setLatinonRevenue(Double latinonRevenue) {
this.latinonRevenue = latinonRevenue;
}
#Column(name="Report_user_revenue")
public Double getUserRevenue() {
return userRevenue;
}
public void setUserRevenue(Double userRevenue) {
this.userRevenue = userRevenue;
}
#Column(name="Report_fill_rate")
public Double getFillRate() {
return fillRate;
}
public void setFillRate(Double fillRate) {
this.fillRate = fillRate;
}
#Column(name="Report_completion_25")
public BigInteger getCompletion25() {
return completion25;
}
public void setCompletion25(BigInteger completion25) {
this.completion25 = completion25;
}
#Column(name="Report_completion_50")
public BigInteger getCompletion50() {
return completion50;
}
public void setCompletion50(BigInteger completion50) {
this.completion50 = completion50;
}
#Column(name="Report_completion_75")
public BigInteger getCompletion75() {
return completion75;
}
public void setCompletion75(BigInteger completion75) {
this.completion75 = completion75;
}
#Column(name="Report_completion_100")
public BigInteger getCompletion100() {
return completion100;
}
public void setCompletion100(BigInteger completion100) {
this.completion100 = completion100;
}
#Column(name="Report_request")
public BigInteger getRequests() {
return requests;
}
public void setRequests(BigInteger requests) {
this.requests = requests;
}
#Column(name="Report_zone")
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
#Column(name="Report_cpm")
public Double getCpm() {
return cpm;
}
public void setCpm(Double cpm) {
this.cpm = cpm;
}
#ManyToOne
#JoinColumn(name="Order_Order_id")
public Order getOrderId() {
return orderId;
}
public void setOrderId(Order orderId) {
this.orderId = orderId;
}
#Override
public String toString() {
return "Report [id=" + id + ", impressions=" + impressions + ", date=" + date + ", grossRevenue=" + grossRevenue
+ ", latinonRevenue=" + latinonRevenue + ", userRevenue=" + userRevenue + ", fillRate=" + fillRate
+ ", completion25=" + completion25 + ", completion50=" + completion50 + ", completion75=" + completion75
+ ", completion100=" + completion100 + ", requests=" + requests + ", zone=" + zone + ", cpm=" + cpm
+ ", orderId=" + orderId + "]";
}
}
User pojo:
package com.latinon.reportator.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="User")
#Inheritance(strategy=InheritanceType.JOINED)
public class User {
private int id;
private String login;
private String password;
private String email;
private Set<Domain> userDomains = new HashSet<Domain>(0);
private Set<Order> userOrders = new HashSet<Order>(0);
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="User_id",nullable=false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="User_login", length=45)
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
#Column(name="User_password", length=45)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="User_mail", length=45)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ManyToMany(fetch=FetchType.LAZY)
public Set<Domain> getUserDomains() {
return userDomains;
}
public void setUserDomains(Set<Domain> userDomains) {
this.userDomains = userDomains;
}
#ManyToMany(fetch=FetchType.LAZY)
public Set<Order> getUserOrders() {
return userOrders;
}
public void setUserOrders(Set<Order> userOrders) {
this.userOrders = userOrders;
}
#Override
public String toString() {
return "User [id=" + id + ", login=" + login + ", password=" + password + ", email=" + email + "]";
}
}
You have in you Report class #Table(name="User"). is this a typo?
Am trying develop backend services with Spring MVC. Here am writing a service which will consume and produce JSON data. I have specified the producing and consuming formats of the service but still am getting the HTTP Status 415.
Model Class Order.java
package com.limitless.engage.models;
import java.util.List;
/**
* Created by Ram K Bharathi on 9/2/2016.
*/
public class Order {
private String order_id;
private int user_id;
private int tableNo;
private String status;
private String time;
private String date;
private transient List<OrderItems> orderItems;
public Order(){
}
public Order(String order_id,int user_id, int tableNo, String status, String time, String date, List<OrderItems> orderItems) {
this.order_id = order_id;
this.user_id = user_id;
this.tableNo = tableNo;
this.status = status;
this.time = time;
this.date = date;
this.orderItems = orderItems;
}
public String getOrder_id() {
return order_id;
}
public void setOrder_id(String order_id) {
this.order_id = order_id;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getTableNo() {
return tableNo;
}
public void setTableNo(int tableNo) {
this.tableNo = tableNo;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String data) {
this.date = data;
}
public List<OrderItems> getOrderItems() {
return orderItems;
}
public void setOrderItems(List<OrderItems> orderItems) {
this.orderItems = orderItems;
}
#Override
public String toString() {
return "Order{" +
"order_id=" + order_id +
", user_id=" + user_id +
", tableNo=" + tableNo +
", status='" + status + '\'' +
", time='" + time + '\'' +
", date='" + date + '\'' +
", orderItems=" + orderItems +
'}';
}
}
Controller Class OrderController.java
package com.limitless.engage.controllers;
import com.limitless.engage.models.Order;
import com.limitless.engage.responses.OrderResponse;
import com.limitless.engage.services.OrderServices;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
/**
* Created by Ram K Bharathi on 9/3/2016.
*/
#RestController
#RequestMapping("/api/order")
public class OrderController {
OrderServices orderServices = new OrderServices();
#RequestMapping(value = "/new", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public ResponseEntity<?> newOrder(#RequestBody Order order)throws Exception{
orderServices.createOrder(order);
OrderResponse orderResponse = new OrderResponse();
orderResponse.setOrderId(order.getOrder_id());
orderResponse.setMessage("success");
return new ResponseEntity<OrderResponse>(orderResponse, HttpStatus.OK);
}
}
I am using Chrome Postman extension for checking the services. I have setted the content-type headers also in Postman.
JSON Object:
{
"order_id":"231",
"user_id":1,
"tableNo":1,
"status":"placed",
"time":"10:00 PM",
"date":"2016-09-04",
"orderItems":[
{
"order_id":"231",
"item_id":1,
"quantity":2,
"taste":"sdbhsfjsdf",
"comment":"shdbfhgeuywe",
"totalPrice":20.00
},
{
"order_id":"231",
"item_id":2,
"quantity":3,
"taste":"sdbhsfjsdf",
"comment":"shdbfhgeuywe",
"totalPrice":45.00
}
]
}