Unable to persist entity (unidirectional many to one relationship) - java

I have a situation where i have an entity OrderedItem which have a many-to-one relationship with another entity Order. When I try to persist the Order entity I receive the following error:
> The bean encountered a non-application exception; nested exception is:
> javax.persistence.PersistenceException: Exception [EclipseLink-4002]
> (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b):
> org.eclipse.persistence.exceptions.DatabaseException Internal
> Exception: com.sap.db.jdbc.exceptions.JDBCDriverException: SAP DBTech
> JDBC: [257]: sql syntax error: incorrect syntax near "ORDER": line 1
> col 13 (at pos 13) Error Code: 257 Call: INSERT INTO ORDER (ID,
> ORDEREDAT, STATUS, TABLE, acceptor_id, waiter_id) VALUES (?, ?, ?, ?,
> ?, ?) bind => [6 parameters bound] Query:
> InsertObjectQuery([Timestamp: 2013-07-16 19:17:56.708 Table: 365
> Status: NEW Waiter: [ID: 1 EGN: 9999999999 Name: Kukata Role: [Role:
> Manager]] Acceptor: [ID: 1 EGN: 9999999999 Name: Kukata Role: [Role:
> Manager]]])
Here is my Order entity
#Entity
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
public static enum Status{
NEW,
PROCESSED
}
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private long id;
#NotNull
#Column(nullable = false)
private Timestamp orderedAt;
#NotNull
#Column(nullable = false)
private Integer table;
#NotNull
#ManyToOne(optional = false)
#JoinColumn(name = "waiter_id", referencedColumnName = "id")
private Employee waiter;
#NotNull
#Enumerated(EnumType.STRING)
private Status status;
#ManyToOne(optional = true)
#JoinColumn(name = "acceptor_id", referencedColumnName = "id")
private Employee acceptor;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Timestamp getOrderedAt() {
return orderedAt;
}
public void setOrderedAt(Timestamp param) {
this.orderedAt = param;
}
public Integer getTable() {
return table;
}
public void setTable(Integer param) {
this.table = param;
}
public Employee getWaiter() {
return waiter;
}
public void setWaiter(Employee param) {
this.waiter = param;
}
public Status getStatus() {
return status;
}
public void setStatus(Status param) {
this.status = param;
}
public Employee getAcceptor() {
return acceptor;
}
public void setAcceptor(Employee param) {
this.acceptor = param;
}
#Override
public String toString() {
return new StringBuilder().append("[Timestamp: ").append(orderedAt)
.append("\tTable: ").append(table).append("\tStatus: ")
.append(status).append("\tWaiter: ").append(waiter)
.append("\tAcceptor: ").append(acceptor).append("]").toString();
}
}
And here is my orderedItem entity
#Entity
#Table(name = "OrderedItem")
public class OrderedItem implements Serializable {
private static final long serialVersionUID = 1L;
public OrderedItem() {
}
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private long id;
#NotNull
#Column(nullable = false)
private Integer quantity;
#NotNull
#Column(nullable = false)
private Double price;
#NotNull
#OneToOne(optional = false)
#JoinColumn(name = "item_id", referencedColumnName = "id")
private Item item;
#NotNull
#ManyToOne(optional = false)
#JoinColumn(name = "order_id", referencedColumnName = "id")
private Order order;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer param) {
this.quantity = param;
}
public Double getPrice() {
return price;
}
public void setPrice(Double param) {
this.price = param;
}
public Item getItem() {
return item;
}
public void setItem(Item param) {
this.item = param;
}
public Order getOrder() {
return order;
}
public void setOrder(Order param) {
this.order = param;
}
#Override
public String toString() {
return new StringBuilder().append("[Order: ").append(order)
.append("Item: ").append(item).append("\tQuantity: ")
.append(quantity).append("\tPrice: ").append(price).append("]")
.toString();
}
}
And my Employee entity
#Entity
#Table(name = "Employee")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
public Employee() {
}
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private long id;
#NotNull
#Column(nullable = false)
private String name;
#NotNull
#Column(nullable = false, unique = true)
private String egn;
#NotNull
#Column(nullable = false)
private byte[] pwd;
#NotNull
#ManyToOne(optional = false)
#JoinColumn(name = "Role_role", referencedColumnName = "role")
private Role role;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String param) {
this.name = param;
}
public String getEGN() {
return egn;
}
public void setEGN(String param) {
this.egn = param;
}
public byte[] getPwd() {
return pwd;
}
public void setPwd(byte[] param) {
this.pwd = param;
}
public Role getRole() {
return role;
}
public void setRole(Role param) {
this.role = param;
}
#Override
public String toString() {
return new StringBuilder().append("[ID: ").append(id).append("\tEGN: ")
.append(egn).append("\tName: ").append(name).append("\tRole: ")
.append(role).append("]").toString();
}
}
Everything works fine, until I try to persist the order entity. Here is a dummy test servlet
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.persistence.dao.CategoryDAO;
import org.persistence.dao.EmployeeDAO;
import org.persistence.dao.ItemDAO;
import org.persistence.dao.OrderDAO;
import org.persistence.dao.OrderedItemDAO;
import org.persistence.dao.RoleDAO;
import sbms.persistence.entities.Category;
import sbms.persistence.entities.Employee;
import sbms.persistence.entities.Item;
import sbms.persistence.entities.Order;
import sbms.persistence.entities.OrderedItem;
import sbms.persistence.entities.Role;
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
private CategoryDAO categoryDAO;
#EJB
private OrderDAO orderDAO;
#EJB
private OrderedItemDAO orderedItemDAO;
#EJB
private ItemDAO itemDAO;
#EJB
private RoleDAO roleDAO;
#EJB
private EmployeeDAO employeeDAO;
public Test() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
response.getWriter().print(
"<p>Checking if the Role 'Manager' exists.</p>");
Role managerRole = null;
List<Role> roles = roleDAO.getAll(
"select X from Role X where X.role = ?1",
Role.ERoles.Manager);
if (roles.size() == 0) {
response.getWriter().print(
"<p>The role 'manager' does not exist. Adding it.</p>");
Role role = new Role();
role.setRole(Role.ERoles.Manager);
roleDAO.add(role);
managerRole = role;
} else {
response.getWriter().print(
"<p>The role 'manager' does exists.</p>");
managerRole = roles.get(0);
}
response.getWriter().print(
"<p>Checking if there are any managers</p>");
List<Employee> employes = employeeDAO.getAll(
"select X from Employee X where X.role = ?1", managerRole);
if (employes.size() == 0) {
response.getWriter().print(
"<p>There are no managers. Adding new one.</p>");
Employee employee = new Employee();
employee.setEGN("9999999999");
employee.setName("Kukata");
employee.setPwd("password".getBytes());
employee.setRole(managerRole);
employeeDAO.add(employee);
}
response.getWriter().print("<p>Checking for category 'Vodka'</p>");
Category category = null;
List<Category> categories = categoryDAO.getAll(
"select X from Category X where X.name = ?1", "Vodka");
if (categories.size() == 0) {
category = new Category();
response.getWriter().print("<p>Adding category Vodka</p>");
category.setName("Vodka");
categoryDAO.add(category);
}else{
category = categories.get(0);
}
response.getWriter().print("<p>Checking for Russian Standard :D</p>");
Item item = null;
List<Item> items = itemDAO.getAll("select X from Item X where X.name = ?1", "RussianStandard");
if(items.size() == 0){
response.getWriter().print(
"<p>Adding item vodka Russian Standard</p>");
item = new Item();
item.setCategory(category);
item.setPrice(35.6);
item.setName("RussianStandard");
itemDAO.add(item);
}else{
item = items.get(0);
}
response.getWriter().print("<p>Making an order</p>");
// Get the employee who accepted the order (in this example -
// Kukata)
List<Employee> acceptor = employeeDAO.getAll(
"select X from Employee X where X.egn = ?1", "9999999999");
if (acceptor.size() == 0) {
response.getWriter().print(
"<p>Error -there is no such employee</p>");
return;
}
Order order = new Order();
order.setStatus(Order.Status.NEW);
order.setOrderedAt(new Timestamp(System.currentTimeMillis()));
order.setTable(365);
// Kuakata accepted and processed the order!
order.setWaiter(acceptor.get(0));
order.setAcceptor(acceptor.get(0));
response.getWriter().print("<p>Persisting the order</p>");
orderDAO.add(order);
response.getWriter().print("<p>Adding the ordered items</p>");
OrderedItem orderedItem = new OrderedItem();
// We set the previously created item(vodka), but we can also get it
// from the db
orderedItem.setItem(item);
orderedItem.setOrder(order);
orderedItem.setPrice(item.getPrice());
orderedItem.setQuantity(5);
orderedItemDAO.add(orderedItem);
response.getWriter().print("<p>Lets see what we have done:</p>");
} catch (Exception e) {
response.getWriter().print(e.getMessage());
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

As Sotirios Delimanolis said in the comments, ORDER is a reserved word in hana. Changing it to something else solves the problem

Related

I'm not able to select particular column from a JPQL?

here is my query where I'm trying to get id and userNotes from Job Class.
#Query("SELECT j.id, j.userNotes FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate")
List<Job> getDriverCalendar(#Param("stDate") Timestamp stDate, #Param("edDate") Timestamp edDate);
Job.java
package com.housecar.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table(name = "hc_job")
public class Job{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "ride_time")
private Timestamp rideTime;
#Column(name = "booking_time")
private Timestamp bookingTime;
#Column(name = "guest_id")
private Long guestId;
#Column(name = "booked_user_id")
private Long bookedUserId;
#Column(name = "car_id")
private Long carId;
#Column(name = "pickup_location")
private String pickupLocation;
#Column(name = "drop_location")
private String dropLocation;
#Column(name = "trip_type")
private Character tripType;
#Column(name = "is_private_job")
private Boolean isPrivateJob;
#Column(name = "estimated_fare")
private BigDecimal estimatedFare;
#Column(name = "actual_fare")
private BigDecimal actualFare;
#Column(name = "tip")
private BigDecimal tip;
#Column(name = "payment_status")
private Character paymentStatus;
#Column(name = "user_notes")
private String userNotes;
#Column(name = "cancellation_notes")
private String cancellationNotes;
#Column(name = "status")
private Character status;
#OneToOne
#JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
private JobDriverRating jobDriverRating;
#OneToOne
#JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
private JobCostSplit jobCostSplit;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getGuestId() {
return guestId;
}
public void setGuestId(Long guestId) {
this.guestId = guestId;
}
public Long getBookedUserId() {
return bookedUserId;
}
public void setBookedUserId(Long bookedUserId) {
this.bookedUserId = bookedUserId;
}
public Long getCarId() {
return carId;
}
public void setCarId(Long carId) {
this.carId = carId;
}
public String getPickupLocation() {
return pickupLocation;
}
public void setPickupLocation(String pickupLocation) {
this.pickupLocation = pickupLocation;
}
public String getDropLocation() {
return dropLocation;
}
public void setDropLocation(String dropLocation) {
this.dropLocation = dropLocation;
}
public Character getTripType() {
return tripType;
}
public void setTripType(Character tripType) {
this.tripType = tripType;
}
public Boolean getIsPrivateJob() {
return isPrivateJob;
}
public void setIsPrivateJob(Boolean isPrivateJob) {
this.isPrivateJob = isPrivateJob;
}
public BigDecimal getEstimatedFare() {
return estimatedFare;
}
public void setEstimatedFare(BigDecimal estimatedFare) {
this.estimatedFare = estimatedFare;
}
public BigDecimal getActualFare() {
return actualFare;
}
public void setActualFare(BigDecimal actualFare) {
this.actualFare = actualFare;
}
public BigDecimal getTip() {
return tip;
}
public void setTip(BigDecimal tip) {
this.tip = tip;
}
public Character getPaymentStatus() {
return paymentStatus;
}
public void setPaymentStatus(Character paymentStatus) {
this.paymentStatus = paymentStatus;
}
public String getUserNotes() {
return userNotes;
}
public void setUserNotes(String userNotes) {
this.userNotes = userNotes;
}
public String getCancellationNotes() {
return cancellationNotes;
}
public void setCancellationNotes(String cancellationNotes) {
this.cancellationNotes = cancellationNotes;
}
public Character getStatus() {
return status;
}
public void setStatus(Character status) {
this.status = status;
}
public JobDriverRating getJobDriverRating() {
return jobDriverRating;
}
public void setJobDriverRating(JobDriverRating jobDriverRating) {
this.jobDriverRating = jobDriverRating;
}
public Timestamp getRideTime() {
return rideTime;
}
public void setRideTime(Timestamp rideTime) {
this.rideTime = rideTime;
}
public Timestamp getBookingTime() {
return bookingTime;
}
public void setBookingTime(Timestamp bookingTime) {
this.bookingTime = bookingTime;
}
public JobCostSplit getJobCostSplit() {
return jobCostSplit;
}
public void setJobCostSplit(JobCostSplit jobCostSplit) {
this.jobCostSplit = jobCostSplit;
}
}
#Query("SELECT j.id, j.userNotes FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate") this query returned [ ].
#Query("SELECT j FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate") this query returned the complete Job object.
Your query doesn't select a Job. It selects two fields. Such a JPQL query returns a List<Object[]>, where each array of the list has two elements.
The return type of the method should thus be changed to List<Object[]>.
In the above query use the alias name for each value fetched
You will get the result as the list of hashmap so change the return type from List<Job> to List<Map> as shown below,
#Query("SELECT j.id as id , j.userNotes as userNotes FROM Job j WHERE j.bookingTime BETWEEN :stDate AND :edDate")
List<Map> getDriverCalendar(#Param("stDate") Timestamp stDate, #Param("edDate") Timestamp edDate);

Deleting child entity from set in parent class

I am trying to attach image files to an entity called product. I can create a product along with the image pretty well but when i try to delete an image i get the following error.
HTTP 500 - Request processing failed; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.IJM.model.Product
Product Class
#Entity
#Table(name = "Product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Id")
private Long id;
#NotNull
#Size(min = 3, max = 10)
#Column(name = "Code", nullable = false)
private String code;
#NotNull
#Size(min = 3, max = 50)
#Column(name = "Name", nullable = false)
private String name;
#Size( max = 50)
#Column(name = "Description", nullable = false)
private String description;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "Id_Category")
private Category category;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "Id_Unit")
private Unit unit;
#OneToMany(cascade = CascadeType.ALL,
fetch= FetchType.EAGER,
orphanRemoval = true,
mappedBy="product")
private Set<Image> images;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
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 Category getCategory() {
return category;
}
public void setCategory(Category category) {
if(this.category==null||!this.category.equals(category))
{
this.category=category;
}
return;
}
public Unit getUnit() {
return unit;
}
public void setUnit(Unit unit) {
if(this.unit==null||!this.unit.equals(unit))
{
this.unit=unit;
}
return;
}
public Set<Image> getImages() {
return images;
}
public void setImages(Set<Image> images) {
this.images = images;
}
}
Image Class
#Entity
#Table(name = "product_Image")
public class Image {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id", nullable = false)
private long id;
#Lob
#Column(name = "File", nullable = false)
private byte[] file;
#Column(name = "Checksum",nullable = false)
private String checksum;
#Column(name = "Extension",nullable = false)
private String extension;
#Column(name = "File_Name",nullable = false)
private String file_name;
#Column(name = "Size",nullable = false)
private int size;
#Column(name = "Last_Updated",nullable = false)
private Timestamp last_Updated;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="Id_Product")
private Product product;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name="Id_Directory")
private Directory directory;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
public String getChecksum() {
return checksum;
}
public void setChecksum(String checksum) {
this.checksum = checksum;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getFile_name() {
return file_name;
}
public void setFile_name(String file_name) {
this.file_name = file_name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public Timestamp getLast_Updated() {
return last_Updated;
}
public void setLast_Updated(Timestamp last_Updated) {
this.last_Updated = last_Updated;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Directory getDirectory() {
return directory;
}
public void setDirectory(Directory directory) {
this.directory = directory;
}
And this is the code for the controller calling the deleting method
#RestController
#RequestMapping("/image")
public class ImageController {
#Autowired
ProductService productService;
#Autowired
ImageService imageService;
private static final String productImagePath="C:\\IJM\\Images\\Product\\";
#RequestMapping(value = "/product/{code}", method = RequestMethod.DELETE)
public ResponseEntity<Image> deleteProductImage(#PathVariable("code") String code) {
System.out.println("Fetching & Deleting Image for product " + code);
code = code.toUpperCase();
if (!productService.isProductExist(code)) {
System.out.println("Product with code " + code + " not found");
return new ResponseEntity<Image>(HttpStatus.NOT_FOUND);
}
else
{
Product product = productService.findProductByCode(code);
if(product.getImages()!=null)
{
for(Image image:product.getImages())
{
product.getImages().remove(image);
image.setProduct(null);
imageService.deleteImage(image.getId());
}
productService.saveProduct(product);
try{
File file = new File(productImagePath+code);
if(FileDeleter.removeDirectory(file)){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
return new ResponseEntity<Image>(HttpStatus.NO_CONTENT);
}
}
In case someone else is wondering.. the service just calls the DAO
#Override
public void deleteImage(long id) {
Image image = imageDao.findById(id);
imageDao.delete(image);
}
This is the Dao Class
#Repository("imageDao")
public class ImageDaoImpl extends AbstractDao<Long,Image> implements ImageDao{
#Override
public void delete(Image image) {
super.delete(image);
}
}
This is the code in my abstract DAO class
public void delete(T entity) {
getSession().delete(entity);
}
It seems these line are not in proper order.
product.getImages().remove(image);
image.setProduct(null);
imageService.deleteImage(image.getId());
Also not sure what imageService.deleteImage(image.getId()); is doing. It is not required.
Please try like below.
for(Image image:product.getImages())
{
image.setProduct(null);
product.getImages().remove(image);
}
productService.saveProduct(product);
This should be enough. I know it doesn't make any sense to change the order but It had worked for me.

Hibernate error: Illegal Attempt to deference collection

Hello I have a one to many relationship between a reservation and rooms and its unidirectional. A reservation might have one to several rooms. Now I'm trying to search if a room is available based on certain dates, and type of room(i.e a king or queen).
My solution:
Find Rooms that are not present in the reservation table based and also based on the date criteria.
Room model:
#Entity
#Table(name="room")
public class Room implements java.io.Serializable {
private static final long serialVersionUID = 10L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="roomId", nullable = false)
private long Id;
#Column(name="roomNumber", length = 4, nullable = false) //room number with max length of 4 digits
private String roomNumber;
#Column(name="type", nullable = false, length=10) //queen or king
private String roomType;
#Column(name="properties", nullable = false, length=15) //smoking or non-smoking
private String roomProperties;
#Column(name="price", columnDefinition = "DECIMAL(10,2)", nullable = false) //sets the precision of price to 2 decimal places
private double price;
public Room() {}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public long getId() {
return Id;
}
public void setId(long id) {
this.Id = id;
}
public String getRoomNumber() {
return roomNumber;
}
public void setRoomNumber(String roomNumber) {
this.roomNumber = roomNumber;
}
public String getRoomType() {
return roomType;
}
public void setRoomType(String roomType) {
this.roomType = roomType;
}
public String getRoomProperties() {
return roomProperties;
}
public void setRoomProperties(String roomProperties) {
this.roomProperties = roomProperties;
}
}
Reservation Table:
#Entity
#Table(name="Reservation")
public class Reservation implements Serializable {
private static final Long serialVersionUID = 100L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="reservation_Id", nullable = false)
private long Id;
public long getId() {
return Id;
}
public void setId(long id) {
Id = id;
}
#Column(name="CheckInDate")
private Date checkInDate;
#Column(name="CheckOutDate")
private Date checkOutDate;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "guestId", nullable = false)
private Guest guest;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "ReservedRooms", joinColumns = {#JoinColumn(name="resId",
referencedColumnName = "reservation_Id")}, inverseJoinColumns = {#JoinColumn(name="roomId",
referencedColumnName = "roomId")})
private List<Room> roomList;
#Column(name="roomsWanted")
private int roomsWanted;
public int getRoomsWanted() {
return roomsWanted;
}
public void setRoomsWanted(int roomsWanted) {
this.roomsWanted = roomsWanted;
}
public Date getCheckInDate() {
return checkInDate;
}
public void setCheckInDate(Date checkInDate) {
this.checkInDate = checkInDate;
}
public Date getCheckOutDate() {
return checkOutDate;
}
public void setCheckOutDate(Date checkOutDate) {
this.checkOutDate = checkOutDate;
}
public Guest getGuest() {
return guest;
}
public void setGuest(Guest guest) {
this.guest = guest;
}
public List<Room> getRoomList() {
return roomList;
}
public void setRoomList(List<Room> roomList) {
this.roomList = roomList;
}
}
Now method to perform the search availability:
#Override
#Transactional
#SuppressWarnings("unchecked")
public boolean checkAvailability(SearchCriteria searchCriteria) {
String hql = "from Room as r where r.roomType = :roomType1 and r.roomProperties = :roomProperties1 " +
"and r.Id not in (Select res.roomList.Id from Reservation as res left outer join res.roomList " +
"where res.checkInDate <=:checkInDate1 and res.checkOutDate >= :checkOutDate1 " +
" and R.Id = res.roomList.Id) ";
Query query = getSession().createQuery(hql);
query.setParameter("roomType1", searchCriteria.getRoomType());
query.setParameter("roomProperties1", searchCriteria.getRoomProperties());
query.setParameter("checkInDate1", searchCriteria.getCheckInDate());
query.setParameter("checkOutDate1", searchCriteria.getCheckOutDate());
List<Room> roomList = query.list();
if(roomList.isEmpty()) {
return true;
}
return false;
}
But it complains and gives the error:
illegal attempt to dereference collection [reservatio1_.reservation_Id.roomList] with element property reference [Id]
Please what I'm doing wrong as I'm new to hibernate
When you join a collection, you have to name it. You can't use it directly (dereference).
in (Select ROOMS.Id from Reservation as res
left outer join res.roomList AS ROOMS
where res.checkInDate <=:checkInDate1 and res.checkOutDate >= :checkOutDate1
and R.Id = ROOMS.Id)

JsonMappingException with Arrays of object in spring-jpa

i get an error when i try to get an item from my dbms. following error
com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.pharmawizardcabinet.core.entity.cabinet.Cabinet.listaFarmaci, could not initialize proxy - no Session (through reference chain: com.pharmawizardcabinet.web.beans.ResponseCabinet["cabinet"]->com.pharmawizardcabinet.core.entity.cabinet.Cabinet["listaFarmaci"])
this is my conteiner
#Entity
#Table(name = "Cabinet")
public class Cabinet implements Serializable {
private static final long serialVersionUID = 7311927404447970875L;
#Id
#Column(name = "Id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "cabinet")
private List<Farmaco> listaFarmaci;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "user")
private User user;
#Column(name = "timestamp")
#Temporal(TemporalType.DATE)
private Date setLastModified;
public Cabinet() {
}
#PostPersist
#PostUpdate
private void setLastUpdate() {
this.setLastModified = new Date();
}
public List<Farmaco> getListaFarmaci() {
return listaFarmaci;
}
public void setListaFarmaci(List<Farmaco> listaFarmaci) {
this.listaFarmaci = listaFarmaci;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public Date getSetLastModified() {
return setLastModified;
}
public void setSetLastModified(Date setLastModified) {
this.setLastModified = setLastModified;
}
}
and this is the item
#Entity
#Table(name = "Farmaco")
public class Farmaco implements Serializable {
private static final long serialVersionUID = -152536676742398255L;
public Farmaco() {
// TODO Auto-generated constructor stub
}
#Column(name = "nome_farmaco")
private String nome;
#Column(name = "codice")
private String codice;
#Column(name = "azienda")
private String azienda;
#Id
#Column(name = "Id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;
#Column(name = "scadenza")
#Temporal(TemporalType.DATE)
private Date scadenza;
#Enumerated(EnumType.STRING)
#Column(name = "posologia")
private Posologia posologia;
#Column(name = "quantita")
private Integer quantita;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "note")
private Note note;
#ManyToOne(cascade =CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "cabinet_id")
private Cabinet cabinet;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCodice() {
return codice;
}
public void setCodice(String codice) {
this.codice = codice;
}
public String getAzienda() {
return azienda;
}
public void setAzienda(String azienda) {
this.azienda = azienda;
}
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public Date getScadenza() {
return scadenza;
}
public void setScadenza(Date scadenza) {
this.scadenza = scadenza;
}
public Posologia getPosologia() {
return posologia;
}
public void setPosologia(Posologia posologia) {
this.posologia = posologia;
}
public Integer getQuantita() {
return quantita;
}
public void setQuantita(Integer quantita) {
this.quantita = quantita;
}
public Note getNote() {
return note;
}
public void setNote(Note note) {
this.note = note;
}
public Cabinet getCabinet() {
return cabinet;
}
public void setCabinet(Cabinet cabinet) {
this.cabinet = cabinet;
}
}
controller is this
#Component("managerCabinet")
public class ManagerCabinet {
private static Logger logger = Logger.getLogger(ManagerCabinet.class);
#PersistenceContext(name = "pwcabinet-jpa")
private EntityManager entityManager;
#Transactional
public Cabinet getCabinetByUser(User user) {
logger.debug("[getCabinetByUser] user: " + user.getId());
return _getCabinetByUser(user);
}
private Cabinet _getCabinetByUser(User user) {
logger.debug("[_getCabinetByUser] user: " + user.getId());
User find = entityManager.find(User.class, user.getId());
Query searchCabinetByUser = entityManager.createQuery("Select c from Cabinet c where c.user = :userId", Cabinet.class);
searchCabinetByUser.setParameter("userId", find);
Cabinet cabinetSearch = (Cabinet) searchCabinetByUser.getSingleResult();
cabinetSearch.setUser(find);
return cabinetSearch;
}
}
but i continue to get error.
if i use the annotation #JsonIgnore in this way
#JsonIgnore
public List<Farmaco> getListaFarmaci() {
return listaFarmaci;
}
they works, but i need this information in my result. how i solve it?
When your method private Cabinet _getCabinetByUser(User user) returns the Cabinet instance is then in the 'detached' state, viz. is no longer associated with a persistence context.
When an item is in a detached state non-eagerly fetched associations can longer be accessed.
As the default fetch for #OneToMany is Lazy then in your case
#OneToMany(cascade = CascadeType.ALL, mappedBy = "cabinet")
private List<Farmaco> listaFarmaci;
the field listaFarmaci can no longer be accessed once the loaded Cabinet is detached from the persistence context.
You have various means of dealing with this which would include:
Marking the field as being eagerly fetched (not good as will always be eagerly fetched regardless of whether required or not).
Forcing the persistence context to remain open until all processing is done typically referred to as the OpenSessionInView pattern (or anti-pattern) depending on your point of view: http://java.dzone.com/articles/open-session-view-design
Ensuring all data required for use case is initialized before detachment. There are various ways of achieving this:
Simply accessing the collection is some way e.g. by calling size() but this may not work with all JPA providers.
Specifying FETCH JOIN in your JPQL query which loads the Cabinet (although this has side effects). http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Join_Fetching

Accessing Object using JAXB in Spring-JPA application

Please help me in accessing Employee object in the below code using JAXB annotations. The application was developed in JPA SPRING. We are unable to access sub-object properties i.e, Employee properties
RESOURCE CORE FILE
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlRootElement(name="resource")
#Entity
#Table(name = "resource")
public class Resource implements java.io.Serializable {
private Integer resourceId;
private String resourceCode;
private String resourceName;
private String resourceNumber;
private Employee employee;
public Resource() {
}
public Resource(Employee employee,String resourceCode, String resourceName,
String resourceNumber
) {
this.employee = employee;
this.resourceCode = resourceCode;
this.resourceName = resourceName;
this.resourceNumber = resourceNumber;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "resource_id", unique = true, nullable = false)
public Integer getResourceId() {
return this.resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
#Column(name = "resource_code")
public String getResourceCode() {
return this.resourceCode;
}
public void setResourceCode(String resourceCode) {
this.resourceCode = resourceCode;
}
#Column(name = "resource_number")
public String getResourceNumber() {
return this.resourceNumber;
}
public void setResourceNumber(String resourceNumber) {
this.resourceNumber = resourceNumber;
}
#Column(name = "resource_name")
public String getResourceName() {
return this.resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "employee_id")
public Employee getEmployee() {
return this.employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
EMPLOYEE CORE FILE
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlRootElement(name="employee")
#Entity
#Table(name = "employee")
public class Employee implements java.io.Serializable {
private Integer employeeId;
private String employeeCode;
private String employeeName;
private List<Resource> resources = new ArrayList<Resource>(0);
public Employee() {
}
public Employee(String employeeCode, String employeeName,List<Resource> resources
) {
this.employeeCode = employeeCode;
this.employeeName = employeeName;
this.resources = resources;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "employee_id", unique = true, nullable = false)
public Integer getEmployeeId() {
return this.employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
#Column(name = "employee_code")
public String getEmployeeCode() {
return this.employeeCode;
}
public void setEmployeeCode(String employeeCode) {
this.employeeCode = employeeCode;
}
#Column(name = "employee_name")
public String getEmployeeName() {
return this.employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "employee")
public List<Resource> getResources() {
return this.resources;
}
public void setResources(List<Resource> resources) {
this.resources = resources;
}
}
You have to use the FetchType : Eager in RESOURCE CORE FILE of getEmployee() Method. Lazy fetch type is pulling only the parent object. Eager is pulling both.

Categories

Resources