hibernate relations in mysql - java

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?

Related

Spring Boot: How to make entity reflect database column changes?

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;
}

Is this HQL/SQL query possible? Java, Spring Boot

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 + '\'' +
'}';
}
}

how to fetch all data from database using one to many relation hibernate query

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 + "]";
}*/
}

Hibernate error: found shared references

Request processing failed; nested exception is
org.springframework.orm.hibernate5.HibernateSystemException: Found
shared references to a collection:
sabeja.entity.ClassificatorObject.apartmentPayers; nested exception is
org.hibernate.HibernateException: Found shared references to a
collection: sabeja.entity.ClassificatorObject.apartmentPayers
I have been searching solution for 2 days. I found solutions in the stackoverflow, but they didn't help for me. I disabled parts of code, but I haven't caught problem.
ClassificatorObject Entity
package xm.entity;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
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.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.Table;
#Entity
#Table(name="managment_responsibilities_object")
public class ClassificatorObject implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="responsibility_id")
private int responsibilityId;
#Column(name="object_id")
private int objectId;
#Column(name="is_enabled")
private int isEnabled;
#Column(name="by_area")
private int byArea;
#Column(name="by_people")
private int byPeople;
#Column(name="by_flat")
private int byFlat;
#Column(name="is_general")
private int isGeneral;
#Column(name="sort")
private int sort;
#Column(name="not_counting")
private int notCounting;
// #OneToMany(fetch = FetchType.LAZY, mappedBy = "classificatorObject", cascade = CascadeType.ALL)
// #OrderBy("month")
// private Set<ServicePeriod> periods;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name = "service_id", insertable=false, updatable=false)
private Set<ServiceOption> options;
#OneToMany(fetch = FetchType.LAZY)
//#JoinColumn(name = "service_id", insertable=false, updatable=false)
#JoinColumn(
name = "object_id",
referencedColumnName = "object_id",
insertable=false, updatable=false
)
private Set<ApartmentPayer> apartmentPayers;
public Set<ApartmentPayer> getApartmentPayers() {
return apartmentPayers;
}
public void setApartmentPayers(Set<ApartmentPayer> apartmentPayers) {
this.apartmentPayers = apartmentPayers;
}
#Column(name="parent_service_id")
private int parentServiceId;
#Column(name="has_children")
private int hasChildren;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="responsibility_id", insertable=false, updatable=false)
private Classificator classificator;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="parent_service_id", insertable=false, updatable=false)
private ClassificatorObject parentService;
//CONSTRUCTORS:
public ClassificatorObject() {
}
public ClassificatorObject(int responsibilityId, int objectId, int isEnabled, int byArea, int byPeople, int byFlat,
int isGeneral, int sort, int notCounting, Set<ServicePeriod> periods, Set<ServiceOption> options,
int parentServiceId, int hasChildren, Classificator classificator) {
super();
this.responsibilityId = responsibilityId;
this.objectId = objectId;
this.isEnabled = isEnabled;
this.byArea = byArea;
this.byPeople = byPeople;
this.byFlat = byFlat;
this.isGeneral = isGeneral;
this.sort = sort;
this.notCounting = notCounting;
// this.periods = periods;
this.options = options;
this.parentServiceId = parentServiceId;
this.hasChildren = hasChildren;
this.classificator = classificator;
}
//GETTERS SETTERS:
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getResponsibilityId() {
return responsibilityId;
}
public void setResponsibilityId(int responsibilityId) {
this.responsibilityId = responsibilityId;
}
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
public int getIsEnabled() {
return isEnabled;
}
public void setIsEnabled(int isEnabled) {
this.isEnabled = isEnabled;
}
public int getByArea() {
return byArea;
}
public void setByArea(int byArea) {
this.byArea = byArea;
}
public int getByPeople() {
return byPeople;
}
public void setByPeople(int byPeople) {
this.byPeople = byPeople;
}
public int getByFlat() {
return byFlat;
}
public void setByFlat(int byFlat) {
this.byFlat = byFlat;
}
public int getIsGeneral() {
return isGeneral;
}
public void setIsGeneral(int isGeneral) {
this.isGeneral = isGeneral;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public int getNotCounting() {
return notCounting;
}
public void setNotCounting(int notCounting) {
this.notCounting = notCounting;
}
// public Set<ServicePeriod> getPeriods() {
// return periods;
// }
//
// public void setPeriods(Set<ServicePeriod> periods) {
// this.periods = periods;
// }
public Set<ServiceOption> getOptions() {
return options;
}
public void setOptions(Set<ServiceOption> options) {
this.options = options;
}
public int getParentServiceId() {
return parentServiceId;
}
public void setParentServiceId(int parentServiceId) {
this.parentServiceId = parentServiceId;
}
public int getHasChildren() {
return hasChildren;
}
public void setHasChildren(int hasChildren) {
this.hasChildren = hasChildren;
}
public Classificator getClassificator() {
return classificator;
}
public void setClassificator(Classificator classificator) {
this.classificator = classificator;
}
public ClassificatorObject getParentService() {
return parentService;
}
public void setParentService(ClassificatorObject parentService) {
this.parentService = parentService;
}
#Override
public String toString() {
return "ClassificatorObject [id=" + id + ", responsibilityId=" + responsibilityId + ", objectId=" + objectId
+ ", isEnabled=" + isEnabled + ", byArea=" + byArea + ", byPeople=" + byPeople + ", byFlat=" + byFlat
+ ", isGeneral=" + isGeneral + ", sort=" + sort + ", notCounting=" + notCounting + ", parentServiceId="
+ parentServiceId + ", hasChildren=" + hasChildren + "]";
}
}
ApartmentPayer Entity
package sabeja.entity;
import java.math.BigDecimal;
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.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="sb_flat_payers")
public class ApartmentPayer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Column(name="flat_id")
private int flatId;
#Column(name="payer_id")
private int payerId;
#Column(name="object_id")
private int objectId;
#Column(name="area", columnDefinition="Decimal(12,2)")
private BigDecimal area;
#Column(name="people_number")
private int peopleNumber;
#OneToMany(fetch = FetchType.LAZY)
#JoinColumn(name="flatPayer_id", insertable=false, updatable=false)
private Set<ServiceOption> options;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="payer_id", insertable= false, updatable= false)
private User user;
// #ManyToOne(fetch = FetchType.LAZY)
// #JoinColumn(name="object_id", insertable=false, updatable=false)
// private TheObject theObject;
public ApartmentPayer() {
super();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Set<ServiceOption> getOptions() {
return options;
}
public void setOptions(Set<ServiceOption> options) {
this.options = options;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getFlatId() {
return flatId;
}
public void setFlatId(int flatId) {
this.flatId = flatId;
}
public int getPayerId() {
return payerId;
}
public void setPayerId(int payerId) {
this.payerId = payerId;
}
public BigDecimal getArea() {
return area;
}
public void setArea(BigDecimal area) {
this.area = area;
}
public int getPeopleNumber() {
return peopleNumber;
}
public void setPeopleNumber(int peopleNumber) {
this.peopleNumber = peopleNumber;
}
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
// public TheObject getTheObject() {
// return theObject;
// }
//
//
//
// public void setTheObject(TheObject theObject) {
// this.theObject = theObject;
// }
#Override
public String toString() {
return "ApartmentPayer [id=" + id + ", flatId=" + flatId + ", payerId=" + payerId + ", area=" + area
+ ", peopleNumber=" + peopleNumber + "]";
}
}
DAOIMPL
Query<Apartment> queryResult2 = currentSession
.createQuery("SELECT DISTINCT a FROM Apartment a "
+ "JOIN FETCH a.theObject o "
+ "JOIN FETCH o.services s "
+ "JOIN FETCH s.apartmentPayers ap "
// + "LEFT JOIN FETCH s.options op "
// + "JOIN ServicePeriod p ON s.id = p.responsibilities_object_id "
// + "JOIN FETCH ap.user u "
+ "WHERE a.houseId = :object_id "
// + "AND (op.flatPayerId = ap.id OR op.id is NULL) "
//+ "AND (SELECT count(*) FROM DisabledPayer di WHERE di.serviceId = s.id AND di.flatPayerId = ap.id) = 0"
// + "AND (CASE WHEN op.is_disabled = 0 THEN 1 WHEN op.is_disabled = 1 "
// + "THEN 0 END) = 1) OR op.id IS NULL"
, Apartment.class);
This error can happen in some specific cases when you have kind of a 'loop' reference, but in this case you don't have a class with a field that uses this same class.
So the error has to be in a call to the method setApartmentPayers(), you need to check all the calls to the method and ensure that you are not assigning the same collection to two different entities.

could not resolve property Query Exception

I get following exception when I try to display data from EmergencyContact. SurveyData and EmergencyData are related by OneToMany. I'm able to persist the data but not able to retrieve it back.
I want to give a SurveyID as input and get back emergency contacts of that survey. I verified all my setter and getter methods and they look okay. I'm unable to trace where I made mistake. Any help is appreciated.
16:53:42,029 ERROR [stderr] (http-localhost-127.0.0.1-8080-1) Caused by: org.hibernate.QueryException: could not resolve property: survey_id of: masonsurveyejb.businesslogic.EmergencyContact [SELECT emc FROM masonsurveyejb.businesslogic.EmergencyContact emc WHERE emc.survey_id = 11]
My query string looks like below. I receive survey_id variable value as an argument in this method.
"SELECT emc FROM EmergencyContact emc WHERE emc.survey_id = " + survey_id
Following are my EmergencyContact and SurveyData classes
package masonsurveyejb.businesslogic;
import java.io.Serializable;
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.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "EmergencyData")
public class EmergencyContact implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "EMERGENCY_SEQUENCE", sequenceName = "Survey_Seq", initialValue = 100, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EMERGENCY_SEQUENCE")
private Integer contactId;
#Column(name = "Name")
private String emName;
#Column(name = "Phone")
private String emPhone;
#Column(name = "Email")
private String emEmail;
#ManyToOne
#JoinColumn(name = "SurveyID")
private SurveyData surveyData;
public Integer getContactId() {
return contactId;
}
public void setContactId(Integer contactId) {
this.contactId = contactId;
}
public SurveyData getSurveyData() {
return surveyData;
}
public void setSurveyData(SurveyData surveyData) {
this.surveyData = surveyData;
}
public String getEmName() {
return emName;
}
public void setEmName(String emName) {
this.emName = emName;
}
public String getEmPhone() {
return emPhone;
}
public void setEmPhone(String emPhone) {
this.emPhone = emPhone;
}
public String getEmEmail() {
return emEmail;
}
public void setEmEmail(String emEmail) {
this.emEmail = emEmail;
}
}
///////////////////////////////////////////////////////////////////////////////
// #filename: Student.java
// #description: This file is the a simple class which is used as a model
// object for Student.
//
// Modification History
// Date Author Change Reason
// ==== ====== =============
// 2014-02-20 Santosh K Tadikonda Initial Creation
//
///////////////////////////////////////////////////////////////////////////////
package masonsurveyejb.businesslogic;
import java.util.List;
import javax.persistence.CascadeType;
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.OneToMany;
import javax.persistence.SequenceGenerator;
#Entity
public class SurveyData {
#Id
#SequenceGenerator(name = "SURVEY_SEQUENCE", sequenceName = "Survey_Seq", initialValue = 100, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SURVEY_SEQUENCE")
#Column(name = "SurveyID")
private Integer survey_id;
private String firstname;
private String lastname;
private String address;
private String city;
private String state;
private String zipcode;
private String telephone;
private String email;
private String surveydate;
#Column(name = "Likes")
private String chklike;
#Column(name = "Know")
private String radioknow;
private String recommend;
private String raffle;
private String comments;
#OneToMany(mappedBy = "surveyData", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<EmergencyContact> emContacts;
public List<EmergencyContact> getEmContacts() {
return emContacts;
}
public void setEmContacts(List<EmergencyContact> emContacts) {
this.emContacts = emContacts;
}
public Integer getSurvey_id() {
return survey_id;
}
public void setSurvey_id(Integer survey_id) {
this.survey_id = survey_id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSurveydate() {
return surveydate;
}
public void setSurveydate(String surveydate) {
this.surveydate = surveydate;
}
public String getChklike() {
return chklike;
}
public void setChklike(String chklike) {
this.chklike = chklike;
}
public String getRadioknow() {
return radioknow;
}
public void setRadioknow(String radioknow) {
this.radioknow = radioknow;
}
public String getRecommend() {
return recommend;
}
public void setRecommend(String recommend) {
this.recommend = recommend;
}
public String getRaffle() {
return raffle;
}
public void setRaffle(String raffle) {
this.raffle = raffle;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String toString() {
String studentString;
studentString = getSurvey_id() + ";" +getFirstname() + ";" + getLastname() + ";"
+ getAddress() + ";" + getCity() + ";" + getState() + ";"
+ getZipcode() + ";" + getTelephone() + ";" + getEmail() + ";"
+ getSurveydate() + ";" + getChklike() + ";" + getRadioknow()
+ ";" + getRecommend() + ";" + getRaffle() + ";"
+ getComments();
return studentString;
}
}
Following is the method from which I make query
#Override
public ArrayList<EmergencyContact> GetEmergencyContacts(String survey_id) {
try {
if (survey_id == null || survey_id.length() == 0) {
System.out.println("Received a null or empty survey ID.");
return null;
}
System.out.println("Getting emergency contacts for " + survey_id);
String queryStr = "SELECT emc FROM EmergencyContact emc WHERE emc.survey_id = "
+ survey_id;
Query query = entityManager.createQuery(queryStr);
List resultList = query.getResultList();
if (resultList != null && resultList.size() > 0) {
ArrayList<EmergencyContact> emList = new ArrayList<EmergencyContact>();
for (Object result : resultList) {
EmergencyContact emc = new EmergencyContact();
emc = (EmergencyContact) result;
emList.add(emc);
}
return emList;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
You receiving the exception because entity 'EmergencyContact' has no property named 'survey_id'.
Your query should be:
String queryStr = "SELECT emc FROM EmergencyContact emc WHERE emc.surveyData.survey_id = :id";
Query query = entityManager.createQuery(queryStr).setParameter("id", survey_id);
List resultList = query.getResultList();
Please consider 2 things:
Use property names in JPQL query (surveyData.survey_id)
It's better to set query parameters with special method, "setParameter"

Categories