I have a problem with my JPA.
Basically my Couriers are created by the program and the customer and parcels are created by user while running. When I try to add a new parcel I add the object to parcel list in Customer and parcel list in Courier. But it crashes when tries to add to Courier parcel list. I create a courier object before calling my menu in the main class
And it throws the following error:
During synchronization a new object was found through a relationship that was not marked cascade PERSIST: Courier:
Id: 0
Name: null
Vehicle: null.
This is my code:
#Entity
#SequenceGenerator(name="cou_seq", initialValue=1, allocationSize=1)
#SuppressWarnings("SerializableClass")
public class Courier implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator="cou_seq")
private int couId;
private String name;
private String vehicle;
#OneToMany(mappedBy = "courier", cascade = CascadeType.PERSIST)
private List<Parcel> plist = new ArrayList<>();
public Courier(){
}
public Courier(String nameIn, String vehicleIn){
name = nameIn;
vehicle = vehicleIn;
}
public void addParcel(Parcel p1){
plist.add(p1);
p1.setCo(this);
}
public int getCouId() {
return couId;
}
public String getName() {
return name;
}
public String getVehicle() {
return vehicle;
}
public void setCouId(int couId) {
this.couId = couId;
}
public void setName(String name) {
this.name = name;
}
public void setVehicle(String vehicle) {
this.vehicle = vehicle;
}
public List<Parcel> getParcel(){
return plist;
}
public void setParcel(List<Parcel> parcels) {
plist = parcels;
}
#Override
public String toString(){
return "Courier: \nId: " + couId + "\nName: " + name + "\nVehicle: " + vehicle;
}
//CUSTOMER CLASS
#Entity
#SequenceGenerator(name="cus_seq", initialValue=1, allocationSize=1)
#SuppressWarnings("SeralizableClass")
public class Customer implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator="cus_seq")
private int cusId;
private String login;
private String password;
private String fname;
private String lname;
private String dob;
private String address;
private String phoneNo;
private String email;
#OneToMany(mappedBy = "customer")
private List<Parcel> plist = new ArrayList<>();
public Customer(){
}
public Customer(String loginIn, String passwordIn, String fnameIn, String lnameIn, String dobIn, String addressIn, String phoneNoIn, String emailIn){
login = loginIn;
password = passwordIn;
fname = fnameIn;
lname = lnameIn;
dob = dobIn;
address = addressIn;
phoneNo = phoneNoIn;
email = emailIn;
}
public void addParcel(Parcel p) {
plist.add(p);
p.setC(this);
}
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
public String getDob() {
return dob;
}
public String getAddress() {
return address;
}
public String getPhoneNo() {
return phoneNo;
}
public String getEmail() {
return email;
}
public void setFname(String fname) {
this.fname = fname;
}
public void setLname(String lname) {
this.lname = lname;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(String address) {
this.address = address;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public void setEmail(String email) {
this.email = email;
}
public List<Parcel> getParcel(){
return plist;
}
public void setParcel(List<Parcel> parcels) {
plist = parcels;
}
public String toString(){
return "Customer: " + "\nID: " + cusId + "\nLogin: " + login + "\nFirst Name: " + fname + "\nSecond Name: " + lname + "\nDOB: " + dob + "\nAddress: " + address + "\nPhone No: " + phoneNo;
}
}
//PARCEL CLASS
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#DiscriminatorColumn(name = "type")
#SequenceGenerator(name = "par_seq", initialValue = 1, allocationSize = 1)
#SuppressWarnings("SerializableClass")
public class Parcel {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "par_seq")
private int parId;
private double height;
private double width;
private double length;
private double weight;
private String receiver;
#ManyToOne()
#JoinColumn(name = "cuId")
private Customer customer;
#ManyToOne()
#JoinColumn(name = "coId")
private Courier courier;
private static double price;
public Parcel() {
}
public Parcel(double heightIn, double widthIn, double lengthIn, double weightIn, String receiverIn) {
height = heightIn;
width = widthIn;
length = lengthIn;
weight = weightIn;
receiver = receiverIn;
}
public double getHeight() {
return height;
}
public double getWidth() {
return width;
}
public double getLength() {
return length;
}
public double getWeight() {
return weight;
}
public double getPrice() {
return price;
}
public void setHeight(double height) {
this.height = height;
}
public void setWidth(double width) {
this.width = width;
}
public void setLength(double length) {
this.length = length;
}
public void setWeight(double weight) {
this.weight = weight;
}
public void setPrice(double price) {
this.price = price;
}
public double calcSize(double height, double width, double length) {
return height * width * length;
}
public void setC(Customer c) {
this.customer = c;
}
public Customer getC() {
return customer;
}
public void setCo(Courier c1) {
this.courier = c1;
}
public Courier getCo() {
return courier;
}
#Override
public String toString() {
return "Parcel:\nHeight: " + height + "\nWidth: " + width + "\nLength: " + length + "\nWeight: " + weight;
}
}
//JPA method that adds a new parcel
public Parcel createParcel(double heightAdd, double widthAdd, double lengthAdd, double weightAdd, String receiverAdd,String owner,String type){
int id = findCustomerIdByLogin(owner);
Customer c = em.find(Customer.class, id);
Courier co = new Courier();
em.getTransaction().begin();
if(type.equals("INT")){
System.out.println("Inside here");
InternationalParcel int1 = new InternationalParcel(heightAdd, widthAdd, lengthAdd, weightAdd, receiverAdd);
em.persist(int1);
c.addParcel(int1);
//em.persist(int1);
co.addParcel(int1);
em.getTransaction().commit();
return int1;
} else {
NationalParcel nat1 = new NationalParcel(heightAdd, widthAdd, lengthAdd, weightAdd,receiverAdd);
em.persist(nat1);
c.addParcel(nat1);
em.persist(nat1);
co.addParcel(nat1);
em.getTransaction().commit();
return nat1;
}
}
You are adding your Parcel to a Courier that is not persisted in the Database yet.
You have to Persist your Courier Object as well.
Since you told your Courier Object that it should cascade persist its Parcel objects it should actually be enough to just persist the Courer without persisting each parcel on its own:
Parcel parcel;
Customer c = em.find(Customer.class, id);
Courier co = new Courier();
em.getTransaction().begin();
if(type.equals("INT")){
parcel = new InternationalParcel(heightAdd, widthAdd, lengthAdd, weightAdd, receiverAdd);
} else {
parcel = new NationalParcel(heightAdd, widthAdd, lengthAdd, weightAdd,receiverAdd);
}
co.addParcel(parcel);
em.persist(co); // <- This is what you are currently not doing!
em.persist(parcel); // <- this might not be necessary because of cascade persist
c.addParcel(parcel);
em.getTransaction().commit();
return parcel;
Related
I'm trying to parse strig xml using JaxB API.
Below is my code
XML
http://www.devx.com/supportitems/showSupportItem.php?co=38898&supportitem=listing1
Pojo Classes
#XmlRootElement(name = "employees")
public class FileWrapper {
private LinkedHashSet<Employee> employees;
public LinkedHashSet<Employee> getEmployees() {
return employees;
}
#XmlElement(name = "employee")
public void setEmployees(LinkedHashSet<Employee> employees) {
this.employees = employees;
}
}
Employee.java
import javax.xml.bind.annotation.XmlAttribute;
public class Employee {
private String division;
private String firstname;
private String id;
private String title;
private String building;
private String room;
private String supervisor;
private String lastname;
public String getDivision() {
return division;
}
#XmlAttribute
public void setDivision(String division) {
this.division = division;
}
public String getFirstname() {
return firstname;
}
#XmlAttribute
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getId() {
return id;
}
#XmlAttribute
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
#XmlAttribute
public void setTitle(String title) {
this.title = title;
}
public String getBuilding() {
return building;
}
#XmlAttribute
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
#XmlAttribute
public void setRoom(String room) {
this.room = room;
}
public String getSupervisor() {
return supervisor;
}
#XmlAttribute
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getLastname() {
return lastname;
}
#XmlAttribute
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
+ title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
+ ", lastname = " + lastname + "]";
}
}
MainEntry
public class TestEntryPoint {
public static void main(String[] args) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(FileWrapper.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("XML from above link as String");
FileWrapper person = (FileWrapper) unmarshaller.unmarshal(reader);
List<Employee> emp = new ArrayList<Employee>(person.getEmployees());
System.out.println(emp.get(0).getFirstname());
}
}
So when am trying to extract any tag's value its showing null. Is there any problem with my XML's data structure or pojo classes ? I'm stuck in this from last couple of hours.
What am doing wrong ? Canyone suggest please ?
Thanks
Annotations in Employee class refer to XML attributes instead of the elements.
Here is corrected version:
public class Employee {
private String division;
private String firstname;
private String id;
private String title;
private String building;
private String room;
private String supervisor;
private String lastname;
public String getDivision() {
return division;
}
#XmlElement(name = "division")
public void setDivision(String division) {
this.division = division;
}
public String getFirstname() {
return firstname;
}
#XmlElement(name = "firstname")
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getId() {
return id;
}
#XmlAttribute
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
#XmlElement(name = "title")
public void setTitle(String title) {
this.title = title;
}
public String getBuilding() {
return building;
}
#XmlElement(name = "building")
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
#XmlElement(name = "room")
public void setRoom(String room) {
this.room = room;
}
public String getSupervisor() {
return supervisor;
}
#XmlElement(name = "supervisor")
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getLastname() {
return lastname;
}
#XmlElement(name = "lastname")
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
+ title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
+ ", lastname = " + lastname + "]";
}
}
I work on a Java Spring boot app where I get the error of Hot-swap failed and schema change is not implemented and the operation is not supported by the VM. Afterward, the table is truncated and have no data at all.
I have 2 models provided below,
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
#NotNull
#NotEmpty
private String name;
#Column(name = "countryName")
#NotNull
#NotEmpty
private String countryName;
#Column(name = "currencyName")
#NotNull
#NotEmpty
private String currencyName;
/*
* total steps is for the keepign the history of the user movement
* */
#Column(name = "totalSteps")
#Min(value = 0L, message = "The value must be positive")
private int totalSteps;
/*
* current steps is for providing the user reward. We will need to set
* it to zero after processing the user payment
* */
#Column(name = "currentSteps")
#Min(value = 0L, message = "The value must be positive")
private int currentSteps;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RewardList> rewardLists = new ArrayList<>();
public User() {
}
public User(#NotNull #NotEmpty String name, #NotNull #NotEmpty String countryName) {
this.name = name;
this.countryName = countryName;
}
public User(#NotNull #NotEmpty String name, #NotNull #NotEmpty String countryName, #Min(value = 0L, message = "The value must be positive") int totalSteps) {
this.name = name;
this.countryName = countryName;
this.totalSteps = totalSteps;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryName() {
return countryName;
}
public String getCurrencyName() {
return currencyName;
}
public void setCurrencyName(String currencyName) {
this.currencyName = currencyName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public int getTotalSteps() {
return totalSteps;
}
public void setTotalSteps(int totalSteps) {
this.totalSteps = totalSteps;
}
public int getCurrentSteps() {
return currentSteps;
}
public void setCurrentSteps(int currentSteps) {
this.currentSteps = currentSteps;
}
public List<RewardList> getRewardLists() {
return rewardLists;
}
public void setRewardLists(RewardList rl) {
this.rewardLists.add(rl);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
return getTotalSteps() == user.getTotalSteps() &&
getCurrentSteps() == user.getCurrentSteps() &&
getId().equals(user.getId()) &&
getName().equals(user.getName()) &&
getCountryName().equals(user.getCountryName()) &&
getRewardLists().equals(user.getRewardLists());
}
#Override
public int hashCode() {
return Objects.hash(getId(), getName(), getCountryName(), getTotalSteps(), getCurrentSteps(), getRewardLists());
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", countryName='" + countryName + '\'' +
", totalSteps=" + totalSteps +
", currentSteps=" + currentSteps +
'}';
}
}
#Entity
public class RewardList {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "reward")
#Min(value = 0L, message = "The value must be positive")
private double reward;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", nullable = false)
private User user;
public RewardList() {
}
public RewardList(User user) {
this.user = user;
}
public RewardList(#Min(value = 0L, message = "The value must be positive") double reward) {
this.reward = reward;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getReward() {
return reward;
}
public void setReward(double reward) {
this.reward = reward;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RewardList)) return false;
RewardList list = (RewardList) o;
return Double.compare(list.getReward(), getReward()) == 0 &&
getId().equals(list.getId()) &&
getUser().equals(list.getUser());
}
#Override
public int hashCode() {
return Objects.hash(getId(), getReward(), getUser());
}
#Override
public String toString() {
return "RewardList{" +
"id=" + id +
", reward=" + reward +
", user=" + user +
'}';
}
}
The end-point where I have this issue provided below,
// $ curl -X PUT http://localhost:8080/api/v1/users/calculateReward?userId=1 | jq
#PutMapping("/calculateReward")
public ResponseEntity<Object> calculateReward(#RequestParam("userId") Long userId) {
Optional<User> optional = userService.findById(userId);
if (!optional.isPresent()) {
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
User user = optional.get();
double reward = user.getCurrentSteps() * Parameters.REWARD_PER_STEPS_EUR;
RewardList list = new RewardList();
list.setUser(user);
list.setReward(reward);
rewardListService.save(list);
user.setCurrentSteps(0);
user.setRewardLists(list);
userService.save(user);
JSONObject json = new JSONObject();
double convertionRateToEuro = currencyMap.get(user.getCurrencyName());
double rewardConverted = reward * convertionRateToEuro;
json.put("name", user.getName());
json.put("currency", user.getCurrencyName());
json.put("reward", rewardConverted);
return ResponseEntity.status(HttpStatus.CREATED).body(json);
}
Does anyone know what is going on and can provide a solution?
Thank you.
I find the reason and below I provide a solution. We will need to save the models based on the hierarchy. HotSwap doesn't support adding methods or hierarchy changes as indicated by the error messages. It's the limitation of Java HotSwap, not IntelliJ IDEA. The proper way of code sequence will be,
User user = optional.get();
RewardList list = new RewardList();
list.setUser(user);
list.setReward(reward);
user.setCurrentSteps(0);
user.setRewardLists(list);
// first save the User
userService.save(user);
// Then, save the RewardList as it has one to many relations
rewardListService.save(list);
When ever I add new child record I have a garbage value that starts appearing in FK column.Following are my classes and database values.
I am not sure whether I am putting any JPA or hibernate annotation wrong or is it a code issue.
Parent Class:
#Component
#Entity
#NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int parentRef;
private BigDecimal price;
private int prod_ID;
private String prodType;
private String remarks;
private int supplier_ID;
private String UOM;
public Product() {
}
#Column(name = "Name")
public String getName() {
return this.name;
}
#Column(name = "ParentRef")
public int getParentRef() {
return this.parentRef;
}
#Column(name = "Price")
public BigDecimal getPrice() {
return this.price;
}
#Id
#Column(name = "Prod_ID")
public int getProd_ID() {
return this.prod_ID;
}
#Column(name = "ProdType")
public String getProdType() {
return this.prodType;
}
#Column(name = "Remarks")
public String getRemarks() {
return this.remarks;
}
#Column(name = "Supplier_ID")
public int getSupplier_ID() {
return this.supplier_ID;
}
#Column(name = "UOM")
public String getUOM() {
return this.UOM;
}
public void setName(String name) {
this.name = name;
}
public void setParentRef(int parentRef) {
this.parentRef = parentRef;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setProd_ID(int prod_ID) {
this.prod_ID = prod_ID;
}
public void setProdType(String prodType) {
this.prodType = prodType;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public void setSupplier_ID(int supplier_ID) {
this.supplier_ID = supplier_ID;
}
public void setUOM(String UOM) {
this.UOM = UOM;
}
#Override
public String toString() {
return "Name = "+ this.getName() +"\n ParentRef="+this.getParentRef() +"\n Prod ID="+this.getProd_ID() +"\n ProdType= "+getProdType() +"\n Remarks= "+getRemarks()+"\n Supplier_ID="+getSupplier_ID()+"\n UOM = "+getUOM()+"\nPrice ="+getPrice();
}
}
Child Class:
#Entity(name="Productdetail")
public class ProductDetail implements Serializable {
private static final long serialVersionUID = 1L;
#Column(nullable=true , name = "Color")
private String Color;
#Column(nullable=true , name = "Designno")
private String DesignNo;
#Column(nullable=true , name = "Imgpath")
private String ImgPath;
#Column(nullable=true , name = "IsScrap")
private Integer IsScrap;
private Product Prod_ID;
#Id
#TableGenerator(
name="ProdDetailID",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="ProdDetailID",
allocationSize=1)
#GeneratedValue(strategy=GenerationType.TABLE, generator="ProdDetailID")
#Column(name = "Proddetail_ID")
private Integer ProdDetail_ID;
#Column(nullable=true , name = "Remarks")
private String Remarks;
public ProductDetail() {
}
public ProductDetail(String remarks, String imgPath, String designNo, String color, Integer isScrap,
Integer prodDetail_ID) {
super();
Remarks = remarks;
ImgPath = imgPath;
DesignNo = designNo;
Color = color;
IsScrap = isScrap;
//Prod_ID = prod_ID;
ProdDetail_ID = prodDetail_ID;
}
public String getColor() {
return Color;
}
public String getDesignNo() {
return DesignNo;
}
public String getImgPath() {
return ImgPath;
}
public Integer getIsScrap() {
return IsScrap;
}
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="Prod_ID" )
public Product getProd_ID() {
return Prod_ID;
}
public Integer getProdDetail_ID() {
return ProdDetail_ID;
}
public String getRemarks() {
return Remarks;
}
public void setColor(String color) {
Color = color;
}
public void setDesignNo(String designNo) {
DesignNo = designNo;
}
public void setImgPath(String imgPath) {
ImgPath = imgPath;
}
public void setIsScrap(Integer isScrap) {
IsScrap = isScrap;
}
public void setProd_ID(Product prod_ID) {
Prod_ID = prod_ID;
}
public void setProdDetail_ID(Integer prodDetail_ID) {
ProdDetail_ID = prodDetail_ID;
}
public void setRemarks(String remarks) {
Remarks = remarks;
}
}
CONTROLLER:
#PostMapping(value="/save")
private void SaveData(#ModelAttribute ProductDetail productDetail ,#RequestParam("Product") int productID) {
productDetail.setProd_ID( getProductList().get(productID) );
System.out.println(productDetail.getProd_ID());
prodDetailService.save(productDetail);
}
#GetMapping(value = "/NewOrder")
public String NewProduct(Model model) {
model.addAttribute("product", new Product());
model.addAttribute("productDetail", new ProductDetail());
model.addAttribute("order", new Order());
model.addAttribute("orderDetial", new OrderDetail());
model.addAttribute("productList", getProductList());
return "NewOrder"; // Returns page named mentioned
}
protected List<Product> getProductList() {
productlist = new ArrayList<Product>();
productlist = ProdService.findAll();;
return productlist;
}
Database value of child table are :
Prod_ID is containing some unknown values.
ProdDetail_ID Prod_ID Color DesignNo ImgPath IsScrap Remarks
------------- ---------- ----- --------- ------- ------- -------
3 **1946157361** Red design NULL NULL NULL
4 **1946157361** Red design NULL NULL NULL
Parent table is :
Prod_ID Name Price UOM ProdType ParentRef Supplier_ID Remarks
------- ---------- ----- ----- -------- --------- ----------- -------
1 Lawn NULL pcs 2 pcs 1 1 1
2 TestData 2500 Meter 3 0 1 Remarks
Please help me out to solve this issue.
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>();
this is the first time I'm working with Hibernate and I want to make this simple query in Hibernate: sql query
I've tried every thing but every time I get the same error output:
org.hibernate.QueryException: could not resolve property: MetadataForHibernate of: bookshare.entity.hasbooks.HasBooks [SELECT H.MetadataForHibernate FROM
Function I made:
#SuppressWarnings("unchecked")
public List<MetadataForHibernate> getBooksByTitle(int userID, String Title) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(
"SELECT H.MetadataForHibernate FROM HasBooks as H WHERE H.users.id = :userid AND LOWER(H.MetadataForHibernate.title) LIKE LOWER(:title) ORDER BY B.title ASC ");
query.setParameter("userid", userID);
query.setParameter("title", "%" + Title + "%");
List<MetadataForHibernate> books = (List<MetadataForHibernate>) query.list();
tx.rollback();
session.close();
factory.close();
return books;
}
MetadataForHibernate:
#Entity
#Table(name="tblbooks")
public class MetadataForHibernate {
#Id
#Column(name = "bookshareId")
private int bookshareId;
#Column(name="author")
private String author;
#Column(name = "availableToDownload")
private int availableToDownload;
#Column(name = "briefSynopsis")
private String briefSynopsis;
#Column(name="category")
private String category;
#Column(name = "completeSynopsis")
private String completeSynopsis;
#Column(name = "contentId")
private int contentId;
#Column(name = "copyright")
private Date copyright;
#Column(name="downloadFormat")
private String downloadFormat;
#Column(name="dtbookSize")
private int dtbookSize;
#Column(name = "freelyAvailable")
private int freelyAvailable;
#Column(name = "brf")
private int brf;
#Column(name = "daisy")
private int daisy;
#Column(name = "images")
private int images;
#Column(name = "isbn13")
private String isbn13;
#Column(name="language")
private String language;
#Column(name = "publishDate")
private Date publishDate;
#Column(name = "publisher")
private String publisher;
#Column(name = "quality")
private String quality;
#Column(name = "title")
private String title;
#OneToMany(mappedBy="book")
private List<HasBooks> hasBooks;
public MetadataForHibernate(){
hasBooks = new ArrayList<HasBooks>();
}
//Getters & Setters
public List<HasBooks> getHasBooks() {
return hasBooks;
}
public void setHasBooks(List<HasBooks> hasBooks) {
this.hasBooks = hasBooks;
}
public int getFreelyAvailable ()
{
return freelyAvailable;
}
public void setFreelyAvailable (String freelyAvailable)
{
this.freelyAvailable = Integer.parseInt(freelyAvailable);
}
public String getCompleteSynopsis ()
{
return completeSynopsis;
}
public void setCompleteSynopsis (String completeSynopsis)
{
this.completeSynopsis = completeSynopsis;
}
public int getDaisy ()
{
return daisy;
}
public void setDaisy (String daisy)
{
this.daisy = Integer.parseInt(daisy);
}
public Date getCopyright ()
{
return copyright;
}
public void setCopyright (Date copyright)
{
this.copyright = copyright;
}
public int getAvailableToDownload ()
{
return availableToDownload;
}
public void setAvailableToDownload (String availableToDownload)
{
this.availableToDownload = Integer.parseInt(availableToDownload);
}
public int getContentId ()
{
return contentId;
}
public void setContentId (String contentId)
{
this.contentId = Integer.parseInt(contentId);
}
public String getPublisher ()
{
return publisher;
}
public void setPublisher (String publisher)
{
this.publisher = publisher;
}
public int getBookshareId ()
{
return bookshareId;
}
public void setBookshareId (String bookshareId)
{
this.bookshareId = Integer.parseInt(bookshareId);
}
public String getAuthor ()
{
return author;
}
public void setAuthor (String author)
{
this.author = author;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getCategory ()
{
return category;
}
public void setCategory (String category)
{
this.category = category;
}
public String getQuality ()
{
return quality;
}
public void setQuality (String quality)
{
this.quality = quality;
}
public String getIsbn13 ()
{
return isbn13;
}
public void setIsbn13 (String isbn13)
{
this.isbn13 = isbn13;
}
public int getImages ()
{
return images;
}
public void setImages (String images)
{
this.images = Integer.parseInt(images);
}
public String getLanguage ()
{
return language;
}
public void setLanguage (String language)
{
this.language = language;
}
public String getBriefSynopsis ()
{
return briefSynopsis;
}
public void setBriefSynopsis (String briefSynopsis)
{
this.briefSynopsis = briefSynopsis;
}
public int getDtbookSize ()
{
return dtbookSize;
}
public void setDtbookSize (int dtbookSize)
{
this.dtbookSize = dtbookSize;
}
public int getBrf ()
{
return brf;
}
public void setBrf (String brf)
{
this.brf = Integer.parseInt(brf);
}
public Date getPublishDate ()
{
return publishDate;
}
public void setPublishDate (Date publishDate)
{
this.publishDate = publishDate;
}
public String getDownloadFormat ()
{
return downloadFormat;
}
public void setDownloadFormat (String downloadFormat)
{
this.downloadFormat = downloadFormat;
}
#Override
public String toString()
{
return "ClassPojo [freelyAvailable = "+freelyAvailable+", completeSynopsis = "+completeSynopsis+", daisy = "+daisy+", copyright = "+copyright+", availableToDownload = "+availableToDownload+", contentId = "+contentId+", publisher = "+publisher+", bookshareId = "+bookshareId+", author = "+author+", title = "+title+", category = "+category+", quality = "+quality+", isbn13 = "+isbn13+", images = "+images+", language = "+language+", briefSynopsis = "+briefSynopsis+", dtbookSize = "+dtbookSize+", brf = "+brf+", publishDate = "+publishDate+", downloadFormat = "+downloadFormat+"]";
}
public void convertDataOf(BookDetail book) throws ParseException{
DateFormat format;
Date date;
this.bookshareId=book.getBookshare().getBook().getMetadata().getBookshareId();
this.author=String.join(",", book.getBookshare().getBook().getMetadata().getAuthor());
this.availableToDownload=book.getBookshare().getBook().getMetadata().getAvailableToDownload();
this.briefSynopsis=book.getBookshare().getBook().getMetadata().getBriefSynopsis();
this.category=String.join(",", book.getBookshare().getBook().getMetadata().getCategory());
this.completeSynopsis=book.getBookshare().getBook().getMetadata().getCompleteSynopsis();
this.contentId=book.getBookshare().getBook().getMetadata().getContentId();
//convert String to date
format = new SimpleDateFormat("yyyy");
date = format.parse(book.getBookshare().getBook().getMetadata().getCopyright());
this.copyright=date;
this.downloadFormat=String.join(",", book.getBookshare().getBook().getMetadata().getDownloadFormat());
this.dtbookSize=book.getBookshare().getBook().getMetadata().getDtbookSize();
this.freelyAvailable=book.getBookshare().getBook().getMetadata().getFreelyAvailable();
this.brf=book.getBookshare().getBook().getMetadata().getBrf();
this.daisy=book.getBookshare().getBook().getMetadata().getDaisy();
this.images=book.getBookshare().getBook().getMetadata().getImages();
this.isbn13=book.getBookshare().getBook().getMetadata().getIsbn13();
this.language=String.join(",", book.getBookshare().getBook().getMetadata().getLanguage());
//convert String to date
format = new SimpleDateFormat("MMddyyyy");
date = format.parse(book.getBookshare().getBook().getMetadata().getPublishDate());
this.publishDate=date;
this.publisher=book.getBookshare().getBook().getMetadata().getPublisher();
this.quality=book.getBookshare().getBook().getMetadata().getQuality();
this.title=book.getBookshare().getBook().getMetadata().getTitle();
}
}
HasBooks:
#Entity
#Table(name = "tblhasbooks")
public class HasBooks implements Serializable {
//#Column(name = "Id",unique = true,nullable = false)
#Id
#GeneratedValue()
private int hasBooksId;
#ManyToOne(cascade = CascadeType.ALL)
private Users user;
#ManyToOne(cascade = CascadeType.ALL)
private MetadataForHibernate book;
public MetadataForHibernate getBook() {
return book;
}
public Users getUser() {
return user;
}
public int getHasBooksId() {
return hasBooksId;
}
public void setHasBooksId(int hasBooksId) {
this.hasBooksId = hasBooksId;
}
public void setUser(Users user) {
this.user = user;
}
public void setBook(MetadataForHibernate book) {
this.book = book;
}
}
Users:
#Entity
#Table(name="tblusers")
public class Users implements Serializable{
public Users(){hasBooks = new ArrayList<HasBooks>();
}
#Id
#Column(name = "Id",unique = true,nullable = false)
#GeneratedValue(strategy=GenerationType.AUTO)
private int Id;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#OneToMany(mappedBy="user")
private List<HasBooks> hasBooks;
//Getters & Setters
public List<HasBooks> getHasBooks() {
return hasBooks;
}
public void setHasBooks(List<HasBooks> hasBooks) {
this.hasBooks = hasBooks;
}
public int getId() {
return Id;
}
public void setUser_id(int Id) {
this.Id = Id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
You need to specify a property name, not a property type.
SELECT H.MetadataForHibernate FROM HasBooks as H
need to be corrected to
SELECT H.book FROM HasBooks H
And you need a join to check a book properties
SELECT book
FROM HasBooks H inner join H.book book
where book.title :=title
The query you have written is not valid Hibernate Query Language (HQL), check the documentation for hints, or you can always use a native query to get an Object[] list from the result set, keeping the query you already have.