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
}
]
}
Related
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;
}
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 am new to JPA and I am trying to persist an Entity that will run through 3 stages New, Processing and Completed. I want the below timestamps to be updated accordingly
#Entity
#Table(name = "feedertable")
#JsonIgnoreProperties(value = { "processStatus" })
public class FeederTable {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private String id;
private String orderID;
private String status;
#Column(name="CREATEDDATETIME",nullable = false)
private Timestamp createdDateTime;
#Column(name="PROCESSSTATUS",nullable = false)
private String processStatus;
#Column(name="HOSTNAME",nullable = true)
private String hostName;
//#Temporal(TemporalType.TIMESTAMP)
#Column(name="PROCESSINGDATETIME",nullable = false)
private Timestamp processingDateTime;
#Column(name="COMPLETEDDATETIME",nullable = false)
private Timestamp completedDateTime; public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Timestamp getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(Timestamp createdDateTime) {
this.createdDateTime = createdDateTime;
}
public String getProcessStatus() {
return processStatus;
}
public void setProcessStatus(String processStatus) {
this.processStatus = processStatus;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public Timestamp getProcessingDateTime() {
return processingDateTime;
}
public void setProcessingDateTime(Timestamp processingDateTime) {
this.processingDateTime = processingDateTime;
}
public Timestamp getCompletedDateTime() {
return completedDateTime;
}
public void setCompletedDateTime(Timestamp completedDateTime) {
this.completedDateTime = completedDateTime;
}
#Override
public String toString() {
return "FeederTable{" +
"id='" + id + '\'' +
", orderID='" + orderID + '\'' +
", status='" + status + '\'' +
", createdDateTime=" + createdDateTime +
", processStatus='" + processStatus + '\'' +
", hostName='" + hostName + '\'' +
", processingDateTime=" + processingDateTime +
", completedDateTime=" + completedDateTime +
'}';
}
Persist in JPARepository:
FeederTable feederTable = new FeederTable();
feederTable.setOrderID(orderId);
feederTable.setStatus(status);
feederTable.setCreatedDateTime(new Timestamp(format.getTime())); feederTable.setProcessStatus("New");
feederTable.setHostName(hostname);
feederTable.setCompletedDateTime(null);
feederTable.setProcessingDateTime(null);
repository.save(feederTable);
However when first time the Entity is persisted, All the Timestamps are populated. I want the PROCESSINGDATETIME and COMPLETEDDATETIME as null and populate it only when it reaches corresponding status. Any idea how to acheive it?.
I did a similar thing in my project using #PrePersist and #PreUpdate annotations.
There are other lifecycle hooks that you can use. Read about them here.
MyEntity{
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#Temporal(TemporalType.TIMESTAMP)
private Date updationDate;
#PrePersist
public void onCreate() {
creationDate = new Date();
}
#PreUpdate
public void onUpdate() {
updationDate = new Date();
}
}
Did I understand your question correctly? Is this what you were looking for?
Using Hibernate 3.6.0
I'm having a real hard time understanding hibernate. I keep running into this issue with lazy initialization exception.
I have an Event entity with a one-to-many relationship with RSVP. When a run a test get back a list of events it works. But when I'm making the call in my controller in order to return it as json, I run into this lazy init error.
This is my event class
#Entity
#Table(name = "EVENT")
public class Event implements Serializable {
#SequenceGenerator(name="event", sequenceName="EVENT_PK_SEQ")
#GeneratedValue(generator="event",strategy=GenerationType.SEQUENCE)
#Id
#Column(name = "EVENT_ID")
private int id;
#Column(name = "DATE_TIME")
private Date date;
#Column(name = "EVENT_NAME")
private String name;
#Column(name = "EVENT_PARTICIPANT_LIMIT")
private int limit;
#Column(name = "EVENT_VISIBILITY")
private boolean visibilty;
#Column(name = "EVENT_LOCATION")
private String location;
#Column(name = "EVENT_DESCRIPTION")
private String description;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private User author;
private Date create_date;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private EventType eventType;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private EventClass eventClass;
#OneToMany(cascade = CascadeType.ALL)
private Set<RSVP> rsvps = new HashSet<RSVP>();
#ManyToMany(mappedBy="event")
private Set<Group> groups = new HashSet<Group>();
public Event(int id, Date date, String name, int limit, boolean visibilty, String location, String description,
User author, Date create_date, EventType eventType, EventClass eventClass) {
super();
this.id = id;
this.date = date;
this.name = name;
this.limit = limit;
this.visibilty = visibilty;
this.location = location;
this.description = description;
this.author = author;
this.create_date = create_date;
this.eventType = eventType;
this.eventClass = eventClass;
}
public Event(){
super();
}
#Override
public String toString() {
return "Event [id=" + id + ", date=" + date + ", name=" + name + ", limit=" + limit + ", visibilty=" + visibilty
+ ", location=" + location + ", description=" + description + ", author=" + author + ", create_date="
+ create_date + ", eventType=" + eventType + ", eventClass=" + eventClass + ", rsvps=" + rsvps
+ ", groups=" + groups + "]";
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public boolean isVisibilty() {
return visibilty;
}
public void setVisibilty(boolean visibilty) {
this.visibilty = visibilty;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}
public EventType getEventType() {
return eventType;
}
public void setEventType(EventType eventType) {
this.eventType = eventType;
}
public EventClass getEventClass() {
return eventClass;
}
public void setEventClass(EventClass eventClass) {
this.eventClass = eventClass;
}
public Set<RSVP> getRsvps() {
return rsvps;
}
public void setRsvps(Set<RSVP> rsvps) {
this.rsvps = rsvps;
}
public Set<Group> getGroups() {
return groups;
}
public void setGroups(Set<Group> groups) {
this.groups = groups;
}
}
My RSVP
#Entity
#Table(name="RSVP")
public class RSVP {
#Id
#Column(name="RSVP_ID")
#SequenceGenerator(name="rsvp", sequenceName="RSVP_PK_SEQ")
#GeneratedValue(generator="rsvp",strategy=GenerationType.SEQUENCE)
private int rsvpId;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
#JoinColumn(name="STATUS_ID")
private RSVPStatus status;
#ManyToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="EVENT_ID")
private Event event;
public RSVP(int rsvpId, RSVPStatus status, User user, Event event) {
super();
this.rsvpId = rsvpId;
this.status = status;
this.user = user;
this.event = event;
}
public RSVP() {
}
#Override
public String toString() {
return "RSVP [rsvpId=" + rsvpId + ", status=" + status + ", user=" + user + ", event=" + event + "]";
}
public int getRsvpId() {
return rsvpId;
}
public void setRsvpId(int rsvpId) {
this.rsvpId = rsvpId;
}
public RSVPStatus getStatus() {
return status;
}
public void setStatus(RSVPStatus status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
}
MY controller
public class MyController {
private static SessionFactory sf = HibernateUtils.getSessionFactory();
private DataFacade df = new DataFacade(sf);
#RequestMapping(value="home", method=RequestMethod.GET,
consumes= MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<List<Event>> getUserCal(){
DataFacade df = new DataFacade(sf);
List<Event> events= df.getAllEventsByAuthor(1);
for(Event e:events){
System.out.println(e);
}
return new ResponseEntity<List<Event>>(events,HttpStatus.OK);
}
}
Your RSVP collection is fetched lazily. (If you don't specify a fetch type, the default is lazy). You need to change it to eager if you are planning to access it after the Hibernate session is closed:
#OneToMany(cascade = CascadeType.ALL, fetch= FetchType.EAGER)
private Set<RSVP> rsvps = new HashSet<RSVP>();
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?