I have three classes which are connected to each other. Order, OrderDetail and Product. When I do in my JPA project the following:
#Override
public Order getOrderById(String orderID) {
Order order = (Order)
em.createQuery("select A from Order A where A.orderId = ?1")
.setParameter(1, orderID)
.getSingleResult();
return order;
}
all the info is retrieved. However, when I move it to the ebj project. I only get Order and that's it. All classes are however included in both the persistence.xml files (JPA and ejb3). Why is that and how should i solve it? The three classes are displayed underneath. I'm using Oracle Weblogic 10.3.3. I tried restarting and clearing the server but that didn't work.
*package eshop;
import java.io.Serializable;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;*
/**
* The persistent class for the orders database table.
*
*/
#Entity
#Table(name="orders")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="order_id")
private String orderId;
#Column(name="cc_expiry")
private String ccExpiry;
#Column(name="cc_name")
private String ccName;
#Column(name="cc_number")
private String ccNumber;
#Column(name="delivery_address")
private String deliveryAddress;
#Column(name="delivery_name")
private String deliveryName;
#Column(name="delivery_surname")
private String deliverySurname;
private String status;
//bi-directional many-to-one association to OrderDetail
#OneToMany(mappedBy="order", cascade=CascadeType.PERSIST)
private List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
public void addOrUpdateOrderDetail(Product product) {
this.orderDetails.add(new OrderDetail(product));
}
public Order() {
}
public String getOrderId() {
return this.orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getCcExpiry() {
return this.ccExpiry;
}
public void setCcExpiry(String ccExpiry) {
this.ccExpiry = ccExpiry;
}
public String getCcName() {
return this.ccName;
}
public void setCcName(String ccName) {
this.ccName = ccName;
}
public String getCcNumber() {
return this.ccNumber;
}
public void setCcNumber(String ccNumber) {
this.ccNumber = ccNumber;
}
public String getDeliveryAddress() {
return this.deliveryAddress;
}
public void setDeliveryAddress(String deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
public String getDeliveryName() {
return this.deliveryName;
}
public void setDeliveryName(String deliveryName) {
this.deliveryName = deliveryName;
}
public String getDeliverySurname() {
return this.deliverySurname;
}
public void setDeliverySurname(String deliverySurname) {
this.deliverySurname = deliverySurname;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public List<OrderDetail> getOrderDetails() {
return this.orderDetails;
}
public void setOrderDetails(List<OrderDetail> orderDetails) {
this.orderDetails = orderDetails;
}
}
package eshop;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
/**
* The persistent class for the order_details database table.
*
*/
#Entity
#Table(name="order_details")
public class OrderDetail implements Serializable {
private static final long serialVersionUID = 1L;
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private BigDecimal price;
private int quantity;
//bi-directional many-to-one association to Order
#ManyToOne
#JoinColumn(name="order_id")
private Order order;
//bi-directional many-to-one association to Product
#ManyToOne
#JoinColumn(name="product_id")
private Product product;
#Id
private int product_id;
public OrderDetail() {
}
public OrderDetail (Integer ProductId,Product product,Integer productQuantity,BigDecimal price, Order order) {
this.price= price;
this.product_id = ProductId;
this.product = product;
this.quantity = productQuantity;
this.order = order;
}
public OrderDetail(Product product1) {
product_id = product1.getCategoryId();
price = product1.getPrice();
quantity = 1;
product = product1;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getQuantity() {
return this.quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Order getOrder() {
return this.order;
}
public void setOrder(Order order) {
this.order = order;
}
public Product getProduct() {
return this.product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
}
package eshop;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
/**
* The persistent class for the products database table.
*
*/
#Entity
#Table(name="products")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="product_id")
private int productId;
#Column(name="category_id")
private int categoryId;
#Lob
private String descr;
private BigDecimal price;
#Column(name="product_name")
private String productName;
private int quantity;
public Product() {
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getCategoryId() {
return this.categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getDescr() {
return this.descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getQuantity() {
return this.quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
As it appeared I had to add transaction type JTA to the ejb's web.xml file.
I don't understand what you mean by "moving the code from the JPA project to the EJB project). Also, can you be a bit more specific about your problem? What makes you say that the objects are not loaded? Where is the code that invokes getOrderById()?
I suspect that it is in the web tier. In that case, I suspect that you may have an issue with the fetch type. By default, it is defined as LAZY (vs EAGER).
This means that JPA will initially load only the root object. It is when you try to access the linked objects that JPA will issue other requests. That will be transparent to the developer, with an important requirement: it will work only when you are in EJB tier. If you have returned the root object to the web tier, then it is "detached" and is not controlled by JPA any more. This means that if the dependent objects have not been loaded, then you will get null values when accessing them (follow-up requests will not be sent to the DB, because JPA is out of the loop).
Related
I recently created a vehicle management system
The system is derived from MySQL database and server side in spring
I want to create another table (automatically at runtime) that will display only 2 of the columns of the existing table.
And the question is what am I doing wrong?
Final goal - when adding / deleting / editing a vehicle, both tables will work in sync and without collisions
I would be happy for your help
Below is the "Car" class
import javax.persistence.*;
import java.time.LocalDate;
#Entity
#Table(name = "car")
public class Car {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long carId;
private String licensePlate;
private int carType;
private boolean suv;
private int engineCapacity;
private int year;
private String note;
private int status;
private LocalDate careDate;
private LocalDate editDate;
public Car() {
}
public Car(long carId) {
this.carId = carId;
}
public long getCarId() {
return carId;
}
public void setCarId(long carId) {
this.carId = carId;
}
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public int getCarType() {
return carType;
}
public void setCarType(int carType) {
this.carType = carType;
}
public boolean isSuv() {
return suv;
}
public void setSuv(boolean SUV) {
this.suv = SUV;
}
public int getEngineCapacity() {
return engineCapacity;
}
public void setEngineCapacity(int engineCapacity) {
this.engineCapacity = engineCapacity;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public LocalDate getCareDate() {
return careDate;
}
public void setCareDate(LocalDate careDate) {
this.careDate = careDate;
}
public LocalDate getEditDate() {
return editDate;
}
public void setEditDate(LocalDate editDate) {
this.editDate = editDate;
}
}
And CarType class which need only to create another MySQL table with the related columns (car_id and car_type)
package com.example.CarSystemMatanElbaz.model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
#Entity
public class CarType {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY,orphanRemoval = true)
#JoinColumn(name= "car_id")
private Car carId;
#OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY,orphanRemoval = true)
#JoinColumn(name= "car_type")
private Car carType;
public CarType() {
}
public CarType(long id, Car carId, Car carType) {
this.id = id;
this.carId = carId;
this.carType = carType;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Car getCarId() {
return carId;
}
public void setCarId(Car carId) {
this.carId = carId;
}
public Car getCarType() {
return carType;
}
public void setCarType(Car carType) {
this.carType = carType;
}
}
Instead of checking and managing flow on the server-side. Just create Replicated Audit Table and making 3 Triggers on the original table like "After Insert, After Update, and After Delete Trigger at MySQL level.
CREATE TRIGGER `db`.`car_AFTER_INSERT` AFTER INSERT ON `trn_student_misc_fees_req_status` FOR EACH ROW
BEGIN
# INSERT Query of Another table using 'NEW' Keyword with car table fields.
END
CREATE TRIGGER `db`.`car_AFTER_UPDATE` AFTER UPDATE ON `trn_student_misc_fees_req_status` FOR EACH ROW
BEGIN
# UPDATE Query of Another table using 'NEW' Keyword with car table fields.
END
CREATE TRIGGER `db`.`car_AFTER_DELETE` AFTER DELETE ON `trn_student_misc_fees_req_status` FOR EACH ROW
BEGIN
# DELETE Query of Another table using 'OLD' Keyword with car table fields.
END
read more about trigger Visit https://www.mysqltutorial.org/mysql-triggers.aspx
as #scaisEdge said also create a view from the table and implement that on your spring project.
car_detailed_view.sql [View]
CREATE
ALGORITHM = UNDEFINED
SQL SECURITY DEFINER
VIEW `car_detailed_view` AS
SELECT
car.carId,car.licensePlate,car.carType,car.suv,car.engineCapacity,car.year,car.note,car.status,car.careDate,car.editDate;
FROM
(`car`
INNER JOIN `CarType` ON ((`car`.`car_id` = `CarType`.`car_id`)))
CarDetailedView.java [View Class]
#Immutable
#Entity
#Table(name = "car_detailed_view")
public class CarDetailedView{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long carId;
private String licensePlate;
private int carType;
private boolean suv;
private int engineCapacity;
private int year;
private String note;
private int status;
private LocalDate careDate;
private LocalDate editDate;
//getter,setter and constructor
}
I am using Spring Boot (v 2.4.0) with Hibernate 5.4.24 and, when trying to get some information from my database, I keep getting this error message:
org.springframework.orm.jpa.JpaSystemException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1
It is kind of weird for me, because it only happens when I try to access the table Shoppingcart, since I can get informatin from the rest of the tables.
I also used the exact same entities with another project but, insetad of using Spring Boot, persistence was made with EntityManagers and it worked perfectly fine.
These are my entities:
Shoppingcart
#Entity
#NamedQuery(name="Shoppingcart.findAll", query="SELECT s FROM Shoppingcart s")
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
private int usID;
//bi-directional many-to-many association to Product
#ManyToMany
#JoinTable(
name="sc_has_product"
, joinColumns={
#JoinColumn(name="scID")
}
, inverseJoinColumns={
#JoinColumn(name="productID")
}
)
private List<Product> products;
//bi-directional one-to-one association to User
#OneToOne(mappedBy="shoppingcart")
private User user;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public int getusID() {
return this.usID;
}
public void setusID(int usID) {
this.usID = usID;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isNull() {
return getProducts().isEmpty();
}
User
#Entity
#Table(name="users")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String address;
#Column(name="card_n")
private Long cardN;
private String city;
private String country;
private int cvv;
private String email;
private String exp;
private String name;
private String pass;
private String surname1;
private String surname2;
private String typeOfUser;
#Column(name="zip_code")
private int zipCode;
//bi-directional many-to-one association to Order
#OneToMany(mappedBy="user")
private List<Orders> orders;
//bi-directional many-to-one association to Product
#OneToMany(mappedBy="user")
private List<Product> products;
//bi-directional one-to-one association to Shoppingcart
#OneToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="ID", referencedColumnName="usID", insertable=false, updatable=false)
private Shoppingcart shoppingcart;
public User() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getCardN() {
return this.cardN;
}
public void setCardN(Long cardN) {
this.cardN = cardN;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public int getCvv() {
return this.cvv;
}
public void setCvv(int cvv) {
this.cvv = cvv;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getExp() {
return this.exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return this.pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getSurname1() {
return this.surname1;
}
public void setSurname1(String surname1) {
this.surname1 = surname1;
}
public String getSurname2() {
return this.surname2;
}
public void setSurname2(String surname2) {
this.surname2 = surname2;
}
public int getZipCode() {
return this.zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public List<Orders> getOrders() {
return this.orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
public Orders addOrder(Orders order) {
getOrders().add(order);
order.setUser(this);
return order;
}
public Orders removeOrder(Orders order) {
getOrders().remove(order);
order.setUser(null);
return order;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Product addProduct(Product product) {
getProducts().add(product);
product.setUser(this);
return product;
}
public Product removeProduct(Product product) {
getProducts().remove(product);
product.setUser(null);
return product;
}
public Shoppingcart getShoppingcart() {
return this.shoppingcart;
}
public void setShoppingcart(Shoppingcart shoppingcart) {
this.shoppingcart = shoppingcart;
}
public String getTypeOfUser() {
return typeOfUser;
}
public void setTypeOfUser(String typeOfUser) {
this.typeOfUser = typeOfUser;
}
}
This is the ShoppingcartDAO class:
public interface ShoppingCartDAO extends CrudRepository<Shoppingcart, Integer> {
#Query("SELECT s FROM Shoppingcart s JOIN User u ON u.id = s.usID AND u.id LIKE :id")
Shoppingcart findByUser(#Param("id") int id);
#Query("SELECT s FROM Shoppingcart s")
List<Shoppingcart> findAllShoppingCart();
}
And, finally, this is my ShoppingcartController class:
#RestController
#CrossOrigin
#EnableAutoConfiguration
public class ShoppingCartController {
#Autowired
ShoppingCartDAO scDAO;
#RequestMapping(value = "sc", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> assignShoppingCart(#RequestBody(required = true) Shoppingcart sc) {
try {
scDAO.save(sc);
return new ResponseEntity<Void>(HttpStatus.CREATED);
} catch(Exception e) {
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
#RequestMapping(value = "sc", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getEveryShoppingCart() {
try {
List<Shoppingcart> sc = scDAO.findAllShoppingCart();
return new ResponseEntity<List<Shoppingcart>>(sc, (sc != null) ? HttpStatus.OK : HttpStatus.NOT_FOUND);
} catch(Exception e) {
System.out.println(e);
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
}
I am really going nuts as I canĀ“t figure out what is going on with my code, so thank you in advance if you help me.
I finally fixed it. For those of you who are wondering how, I deleted the relationships between tables that I had, ending with:
Shoppingcart:
#Entity
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
#Column(name = "usID")
private Integer userID;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
Product:
#Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int productID;
private String category;
private String color;
private String description;
private String estadoProducto;
private String fecha;
private int orderID;
private String photo;
private double price;
private int seller;
private String sexo;
private String state = "Disponible";
private String talla;
private String title;
public Product() {
}
public int getProductID() {
return this.productID;
}
public void setProductID(int productID) {
this.productID = productID;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEstadoProducto() {
return this.estadoProducto;
}
public void setEstadoProducto(String estadoProducto) {
this.estadoProducto = estadoProducto;
}
public String getFecha() {
return this.fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getPhoto() {
return this.photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public String getSexo() {
return this.sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getTalla() {
return this.talla;
}
public void setTalla(String talla) {
this.talla = talla;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public int getSeller() {
return seller;
}
public void setSeller(int seller) {
this.seller = seller;
}
With this, everything worked fine, but don't ask me why, because I don't know it.
Your Getters/Setters are wrongly implemented.
Like :
Actual :
public int getusID() {
return this.usID;
}
Expected :
public int getUsID() {
return this.usID;
}
Same with setter
I have the following configuration and code in my spring boot application but I am not getting a foreign key constraint in mysql can some one help please.
The Stock class:-
#Entity(name = "stock")
public class Stock {
#Id
#Column(name = "p_id")
private String productId;
#Column(name="p_desc")
private String productDescription;
#Column(name="p_quantity")
private double productQuantityInStock;
#Column(name = "p_threshold")
private double productThresholdQuantity;
#OneToOne( cascade = CascadeType.ALL)
#JoinColumn(foreignKey = #ForeignKey(name = "fk_productPrice"),referencedColumnName = "pr_id")
private ProductPrice productPrice;
#ManyToMany(mappedBy = "listOfProducts")
private Set<OrderList> orderLists;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public double getProductQuantityInStock() {
return productQuantityInStock;
}
public void setProductQuantityInStock(double productQuantityInStock) {
this.productQuantityInStock = productQuantityInStock;
}
public double getProductThresholdQuantity() {
return productThresholdQuantity;
}
public void setProductThresholdQuantity(double productThresholdQuantity) {
this.productThresholdQuantity = productThresholdQuantity;
}
public ProductPrice getProductPrice() {
return productPrice;
}
public void setProductPrice(ProductPrice productPrice) {
this.productPrice = productPrice;
}
}
Product Class :-
#Entity(name = "productprice")
public class ProductPrice {
#Id
#Column(name = "pr_id")
private String PriceId;
#Column(name="p_id")
private String ProductId;
#Column(name="price")
private double Price;
public String getPriceId() {
return PriceId;
}
public void setPriceId(String priceId) {
PriceId = priceId;
}
public String getProductId() {
return ProductId;
}
public void setProductId(String productId) {
ProductId = productId;
}
public double getPrice() {
return Price;
}
public void setPrice(double price) {
Price = price;
}
}
Project.properties
Application log for Constraints
Mysql DDL
If you can see the mysql ddl there is no foreign key constraint. I have tried this with all possible combinations in JoinColumn and I could not see Foreign key. And I came to know that just KEY means index in mysql. Which I am not expecting. Any help or material or directions will help. Thanks
I have two table on MySql database. Item, ItemGroup which are related by Item.groupid -> ItemGroup.id I am also using hibernate-entitymanager and spring boot. Here are my entity classes for Item and ItemGroup.
Item.java
package com.thiha.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String createdDate;
private String modifiedDate;
private String itemCode;
private String description;
private int groupId;
private double quantity;
private double price;
private int recordStatus;
private ItemGroup itemGroup;
#ManyToOne
#JoinColumn(name = "groupid")
public ItemGroup getItemGroup() {
return itemGroup;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(String modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getRecordStatus() {
return recordStatus;
}
public void setRecordStatus(int recordStatus) {
this.recordStatus = recordStatus;
}
}
ItemGroup.java
package com.thiha.entities;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class ItemGroup {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String createdDate;
private String modifiedDate;
private String groupCode;
private String groupName;
private int recordStatus;
private List<Item> items;
#OneToMany(mappedBy = "itemGroup", cascade = CascadeType.ALL)
public List<Item> getItems(){
return items;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(String modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getGroupCode() {
return groupCode;
}
public void setGroupCode(String groupCode) {
this.groupCode = groupCode;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public int getRecordStatus() {
return recordStatus;
}
public void setRecordStatus(int recordStatus) {
this.recordStatus = recordStatus;
}
}
I also create a foreign keys in Item table reference to ItemGroup table with foreign key groupid. But when I run the code with mvn spring-boot:run, I got some exception as following:
org.hibernate.MappingException: Could not determine type for: java.util.List, at table: item_group, for columns: [org.hibernate.mapping.Column(items)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:431)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:398)
at org.hibernate.mapping.Property.isValid(Property.java:225)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:595)
at org.hibernate.mapping.RootClass.validate(RootClass.java:265)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:443)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
If I remove the relationships in both class, it is working properly but I cannot make INNER JOIN query. Please help me to solve this problem
You can't mix annotation conventions in Hibernate. Please try to move your #Id and #GeneratedValue annotations to getter, or #OneToMany and #ManyToOne to fields.
It says
Could not determine type for: java.util.List, at table: item_group, for columns: [org.hibernate.mapping.Column(items)]'
Because your mappedBy is incorrect.
When you put annotation on getter getCategory(), hibernate understands that it's category.
#ManyToOne
#JoinColumn(name = "groupid")
public ItemGroup getCategory() {
return itemGroup;
}
So, please use appropriate name in your class ItemGroup
#OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
public List<Item> getItems(){
return items;
}
dont worry there is do only one thing remove your annotation of #Id and #generatorValue annotation above on the id and put on the getter method of your id
the problem will be fix.....!
i am developing a simple Java EE application, that uses database. It has two tables (Admin and Session signature) connected with many to one relation.
When i used eclipse to generate entities from tables, my attribute that links both tables was generated like this:
//bi-directional many-to-one association to Admin
#ManyToOne
#JoinColumn(name="owner")
private Admin admin;
Problem is, my owner attribute is Integer in database, and it has been created as Admin type.
Now when i want to pass some Integer variable to input it to database i get error:
The method setAdmin(Admin) in the type Signaturesession is not applicable for arguments (int).
Or when i want to cast it to (Admin) like this (taking it from session):
(Admin)session.getAttribute("adminId")
I get Jboss Error:
javax.servlet.ServletException: java.lang.ClassCastException: java.lang.Integer cannot be cast to com.podpisy.entities.Admin
javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
secure.SecurityCheckFilter.doFilter(SecurityCheckFilter.java:100)
I am sure that this can be done easy, but i'm just really bad using Java.
Thanks for any help.
EDIT:
My Admin.java class:
package com.podpisy.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name="admins")
#NamedQuery(name="Admin.findAll", query="SELECT a FROM Admin a")
public class Admin implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
private String login;
private String password;
//bi-directional many-to-one association to Signature
#OneToMany(mappedBy="admin")
private List<Signature> signatures;
//bi-directional many-to-one association to Signaturesession
#OneToMany(mappedBy="admin")
private List<Signaturesession> signaturesessions;
public Admin() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return this.login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Signature> getSignatures() {
return this.signatures;
}
public void setSignatures(List<Signature> signatures) {
this.signatures = signatures;
}
public Signature addSignature(Signature signature) {
getSignatures().add(signature);
signature.setAdmin(this);
return signature;
}
public Signature removeSignature(Signature signature) {
getSignatures().remove(signature);
signature.setAdmin(null);
return signature;
}
public List<Signaturesession> getSignaturesessions() {
return this.signaturesessions;
}
public void setSignaturesessions(List<Signaturesession> signaturesessions) {
this.signaturesessions = signaturesessions;
}
public Signaturesession addSignaturesession(Signaturesession signaturesession) {
getSignaturesessions().add(signaturesession);
signaturesession.setAdmin(this);
return signaturesession;
}
public Signaturesession removeSignaturesession(Signaturesession signaturesession) {
getSignaturesessions().remove(signaturesession);
signaturesession.setAdmin(null);
return signaturesession;
}
}
My Signaturesession.class:
package com.podpisy.entities;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the signaturesession database table.
*
*/
#Entity
#NamedQuery(name="Signaturesession.findAll", query="SELECT s FROM Signaturesession s")
public class Signaturesession implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
private String device;
private String name;
private int signatures;
private int time;
private String type;
private int users;
//bi-directional many-to-one association to Admin
#ManyToOne
#JoinColumn(name="owner")
private Admin admin;
public Signaturesession() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getDevice() {
return this.device;
}
public void setDevice(String device) {
this.device = device;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getSignatures() {
return this.signatures;
}
public void setSignatures(int signatures) {
this.signatures = signatures;
}
public int getTime() {
return this.time;
}
public void setTime(int time) {
this.time = time;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public int getUsers() {
return this.users;
}
public void setUsers(int users) {
this.users = users;
}
public Admin getAdmin() {
return this.admin;
}
public void setAdmin(Admin admin) {
this.admin = admin;
}
}
You should pass an Admin object which surely has an int id field.
So you've to make something like this
Admin myAdmin=new Admin(id,.. other properties);
mySignaturesession.setAdmin(myAdmin);
EDIT
Above is valid if you want to associate and Admin to your SignatureSession object. Instead if you have an Admin ojbect in Session you just have to execute
Admin anAdmin=(Admin)session.getAttibute("adminId");
Admin myAdmin=new Admin(id,.. other properties);
or
Admin myAdmin=new Admin();
myAdmin.setId(anId);
But, i repeat, it depends from what you have in the Session and which objects you handle.
And, as you look to be using JPA, dont forget to do something like em.persist or em.merge on your objects.
Maybe you should get a little deeper on how JPA works.