hibernate Mapping One to many relation ship between primary key and composite key - spring

I am struggling with a hibernate mapping problem of mapping One to many relation ship between Primary key of Order Table and composite key of Product Cart with some extra columns
public class OrderDetails implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="ORDERID")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer orderId;
#Column(name="ORDER_DATE")
private Date orderDate= new Date();
//other fields and getter setter
.....
.....
Product Cart table has a composite key CART ID and PRODUCT ID
#Entity
#Table(name="PRODUCT_CART")
#AssociationOverrides({
#AssociationOverride(name="pk.shopCart", joinColumns=#JoinColumn(name="CARTID")),
#AssociationOverride(name="pk.product", joinColumns=#JoinColumn(name="PRODUCTID"))
})
public class ProductCart implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EmbeddedId
private ProductCartId pk = new ProductCartId();
#Column(name="QUANTITY")
private Integer selectedQuantity=1;
#Column(name="TOTAL")
private double total=0.0;
//other fields and getter setter
.....
.....
I tried following but not working
#Entity
#Table(name="PRODUCTCART_ORDERDETAILS")
#AssociationOverrides({
#AssociationOverride(name="pcoPK.orderDetails",joinColumns=#JoinColumn(name="ORDERID")) ,
#AssociationOverride(name="pcoPK.pk", joinColumns=
{#JoinColumn(name="pk.shopCart",referencedColumnName="CARTID"),
#JoinColumn(name="pk.product",referencedColumnName="PRODUCTID") }) })
public class ProductCartOrder implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2348674131019001487L;
#EmbeddedId
private ProductCartOrderId pcoPK = new ProductCartOrderId();
#Column(name="QUANTITY")
private Integer quantity;
#Column(name="PRICE")
private double price;
#Transient
public OrderDetails getOrderDetails(){
return getPcoPK().getOrderDetails();
}
public void setOrderDetails(OrderDetails orderDetails){
getPcoPK().setOrderDetails(orderDetails);
}
#Transient
public ProductCartId getProductCartId(){
return getPcoPK().getPk();
}
public void setProductCartId(ProductCartId pk){
getPcoPK().setPk(pk);
}
Can someone please help me to implement this? Below is the error message
Caused by: org.hibernate.AnnotationException: Illegal attempt to define a #JoinColumn with a mappedBy association: pcoPK.pk
at org.hibernate.cfg.Ejb3JoinColumn.buildJoinColumn(Ejb3JoinColumn.java:152)
at org.hibernate.cfg.Ejb3JoinColumn.buildJoinColumns(Ejb3JoinColumn.java:127)
at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1212)
at org.hibernate.cfg.AnnotationBinder.fillComponent(AnnotationBinder.java:1841)
at org.hibernate.cfg.AnnotationBinder.bindId(AnnotationBinder.java:1878)

After lot of research I could not find the solution I done it in another way.
I created Many to many relationship between OrderDetails and Product with some extra columns ID, price, quantity and inserted value manually for each element in product cart thorugh a for loop.
public class Product implements Serializable {
#OneToMany(mappedBy="product")
private Set<ProductOrder> productOrder;
...//other fields and getter setter
}
public class OrderDetails implements Serializable {
#OneToMany(mappedBy="orderDetails")
private Set<ProductOrder> productOrder;
...//other fields and getter setter
}
public class ProductOrder {
#Id
#Column(name="PRODUCT_ORDER_ID")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int prductOrderId;
#ManyToOne
private OrderDetails orderDetails;
#ManyToOne
private Product product;
...//other fields and getter setter
}
In my controller class where I wanted to save the products of ProductCart I did following
List<ProductCart> productList = new ArrayList<ProductCart>();
productList=productCartService.getCartProducts(shopCart);
ProductOrder orderedProducts = new ProductOrder();
for (ProductCart productCarts : productList) {
orderedProducts.setOrderDetails(orderDetails);
orderedProducts.setProduct(productCarts.getPk().getProduct());
orderedProducts.setPrice(productCarts.getPk().getProduct().getPrice());
orderedProducts.setQuantity(productCarts.getSelectedQuantity());
productOrderService.addOrderProducts(orderedProducts);
}

Related

Remove row from table throws ConstraintViolationException

Im having a problem when i want to delete the product from the database, deleting it, it should be removed from all the orders that contain that product. But when i try to do it this is the error i get:
"error_message": "Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [fkbjvki7e3gm7vrphs73g4x7d2g]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
This is my Order class:
#Entity
#Table(name="orders")
public class Order{
private #Id
#GeneratedValue
Long id;
#OneToMany(mappedBy = "order", cascade = CascadeType.ALL,orphanRemoval = true)
private List<ProductOrderDetails> orderedProducts = new ArrayList<>();
public void addProduct(Product product, int quantity) {
ProductOrderDetails orderedProduct = new ProductOrderDetails(this,product,quantity);
orderedProducts.add(orderedProduct);
product.getProductOrderDetails().add(orderedProduct);
totalOrderPrice+=product.getPrice()*quantity;
}
public void removeProduct(Product product,int quantity) {
ProductOrderDetails orderedProduct = new ProductOrderDetails( this, product,0);
product.getProductOrderDetails().remove(orderedProduct);
orderedProducts.remove(orderedProduct);
orderedProduct.setOrder(null);
orderedProduct.setProduct(null);
totalOrderPrice-=product.getPrice()*quantity;
}
}
This is my Product class
#Entity
#Table
public class Product {
private #Id
#GeneratedValue
Long id;
private String name;
#OneToMany(mappedBy = "order", cascade = CascadeType.MERGE,orphanRemoval = true)
private List<ProductOrderDetails> productOrderDetails = new ArrayList<>();
}
ProductOrderID
#Embeddable
public class ProdOrderId implements Serializable {
#Column(name = "order_id")
private Long orderId;
#Column(name = "product_id")
private Long productId;
}
Many to many column of Products and Orders
#Entity
#Table
public class ProductOrderDetails implements Serializable{
#EmbeddedId
#JsonIgnore
private ProdOrderId id;
#ManyToOne
#MapsId("orderId")
#JsonIgnore
Order order;
#ManyToOne
#MapsId("productId")
Product product;
private int quantity;
}
This is my controller method
#DeleteMapping("/{id}")
ResponseEntity<?> deleteProduct(#PathVariable Long id)
{
repository.deleteById(id);
return ResponseEntity.noContent().build();
}
I don't think this is doing what you think it's doing:
ProductOrderDetails orderedProduct = new ProductOrderDetails( this, product,0);
product.getProductOrderDetails().remove(orderedProduct);
If you debug your code or check the return value of remove you will find that it is returning false, which means nothing was removed.
You're just creating a new ProductOrderDetails and then trying to remove it from product.getProductOrderDetails(), but it doesn't exist in it. You need to find the right element to remove from that collection.

I don't know why the double values are displayed in postman. Is the my code correct?

This is my Book class:
#Entity
#Table(name="book")
public class Book {
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(targetEntity=Category.class,cascade=CascadeType.ALL,fetch=FetchType.LAZY)
#JoinColumn(name="CategoryId")
public Category category;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(length=10)
private int book_id;
#Column(length=128)
private String title;
#Column(length=64)
private String author;
#Column(length=200)
private String description;
#Column(length=10)
private int ISBN;
#Column(length=10)
private float price;
private Date published_Date;
#Lob
#Column
#Basic(fetch = FetchType.LAZY)
private byte[] icon;
//getter and setter
}
This is my Category class:
#Entity
#Table(name="category1")
public class Category {
#Id
#Column(length=12)
#GeneratedValue(strategy=GenerationType.AUTO)
public int CategoryId;
#Column(length=50)
public String CategoryName;
//#JsonBackReference
#OneToMany(mappedBy="category")
private List<Book> books = new ArrayList<Book>();
//getter and setter
}
The relationship between them is one to many.
This is my Category Service class
#Service
#Transactional
public class AdminServiceImpl implements AdminService {
#Autowired
private CategoryDao dao;
#Autowired
private BookDao dao1;
#Override
public List<Category> getAllCategory(){
return dao.findAll();
}
}
My Controller class
#RestController
#RequestMapping("/bookstore")
public class CategoryController {
#Autowired
private AdminService service;
#GetMapping("/GetAllCategory")
private ResponseEntity<List<Category>> getAllCategory() {
List<Category> catlist = service.getAllCategory();
return new ResponseEntity<List<Category>>(catlist, new HttpHeaders(), HttpStatus.OK);
}
}
My category table already has data.When i try to display them it is showing double values.
Displaying values using Postman
The Category table in the Database: Database table
Jackson's ObjectMapper uses the Java bean pattern and it expects the following
public class Foo {
public Object bar;
public Object getBar() {...}
public void setBar(Object bar) {...}
}
The getters and setters start with get and set, respectively, followed by the corresponding field name with its first letter capitalized.
Change
CategoryId to categoryId (first letter lowercase)
and
CategoryName to categoryName

i'm getting null value in a child table as a foreign key of parent table using spring data rest or spring data jpa accosiation

enter image description here In this image first address for empId 1 and last two records are empid 2 (empid 2 haveing to address)
file:///home/user/Pictures/fk.png
#Entity
#Table(name = "Employee")
public class Employee {
#Id
#GeneratedValue
private Integer id;
private String name;
private Integer sal;
#OneToMany(cascade = CascadeType.ALL,mappedBy="employee")
private List<Address> addresses;
//getter setter
Child entity
#Entity(name="Address")
public class Address {
#Id
#GeneratedValue
private Integer aid;
private String city;
private String state;
#ManyToOne
#JoinColumn(name="id")
private Employee employee;
//getter setter
Repository
#Repository
#RepositoryRestResource(path="employee")
public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
}
Input from RestClient
{
"name":"rdhe",
"sal":"20000",
"addresses":[{
"city":"hyd",
"state":"ts"
}]
}
if i use spring data jpa then code will be
// jpa Repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
}
// EmployeeServer class
#Service
public class EmployeeService {
#Autowired
EmployeeRepo employeeRepo;
public void saveEmployee(Employee employee){
employeeRepo.save(employee);
}
}
// controller
#RestController
public class EmployeeController {
#Autowired
EmployeeService employeeService;
#PostMapping(path="/save")
public void saveEmp(#RequestBody Employee employee){
employeeService.saveEmployee(employee);
}
}
if i'll use spring-data-rest at that time no need to create employeeService and controller class
I was getting the same problem until JsonManagedReference came to my rescue.
Try changing your entities to include them like this:
In the Employee Entity:
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy ="employee")
#JsonManagedReference
private List<Address> addresses;
In the Address Entity:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id", nullable = false, updatable = false, insertable =true)
#JsonBackReference
private Employee employee;
I was not able to find why it works this way, so please let me know if you come to know :)
It is probably due to the fact that your mentioning #JoinColumn(name="id"). The name attribute in #JoinColumn defines the name of the foreign key field in the child table. Since you are specifying foreign key column as id on hibernate, it could be the issue. Please update it to the same name(ie fk_empid) as specified in database, it should work...

Spring JPA saving distinct entities with composite primary key not working as expected, updates same entity

I have a logic that saves some data and I use spring boot + spring data jpa.
Now, I have to save one object, and after moment, I have to save another objeect.
those of object consists of three primary key properties.
- partCode, setCode, itemCode.
let's say first object has a toString() returning below:
SetItem(partCode=10-001, setCode=04, itemCode=01-0021, qty=1.0, sortNo=2, item=null)
and the second object has a toString returning below:
SetItem(partCode=10-001, setCode=04, itemCode=01-0031, qty=1.0, sortNo=2, item=null)
there is a difference on itemCode value, and itemCode property is belonged to primary key, so the two objects are different each other.
but in my case, when I run the program, the webapp saves first object, and updates first object with second object value, not saving objects seperately.
(above image contains different values from this post question)
Here is my entity information:
/**
* The persistent class for the set_item database table.
*
*/
#Data
#DynamicInsert
#DynamicUpdate
#Entity
#ToString(includeFieldNames=true)
#Table(name="set_item")
#IdClass(SetGroupId.class)
public class SetItem extends BasicJpaModel<SetItemId> {
private static final long serialVersionUID = 1L;
#Id
#Column(name="PART_CODE")
private String partCode;
#Id
#Column(name="SET_CODE")
private String setCode;
#Id
#Column(name="ITEM_CODE")
private String itemCode;
private Double qty;
#Column(name="SORT_NO")
private int sortNo;
#Override
public SetItemId getId() {
if(BooleanUtils.ifNull(partCode, setCode, itemCode)){
return null;
}
return SetItemId.of(partCode, setCode, itemCode);
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinColumns(value = {
#JoinColumn(name="PART_CODE", referencedColumnName="PART_CODE", insertable=false, updatable=false)
, #JoinColumn(name="ITEM_CODE", referencedColumnName="ITEM_CODE", insertable=false, updatable=false)
})
private List<Item> item;
}
So the question is,
how do I save objects separately which the objects' composite primary keys are partially same amongst them.
EDIT:
The entity extends below class:
#Setter
#Getter
#MappedSuperclass
#DynamicInsert
#DynamicUpdate
public abstract class BasicJpaModel<PK extends Serializable> implements Persistable<PK>, Serializable {
#Override
#JsonIgnore
public boolean isNew() {
return null == getId();
}
}
EDIT again: embeddable class.
after soneone points out embeddable class, I noticed there are only just two properties, it should be three of it. thank you.
#Data
#NoArgsConstructor
#RequiredArgsConstructor(staticName="of")
#Embeddable
public class SetGroupId implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#NonNull
private String partCode;
#NonNull
private String setCode;
}
Check howto use #EmbeddedId & #Embeddable (update you might need to use AttributeOverrides in id field, not sure if Columns in #Embeddable works).
You could create class annotated #Embeddable and add all those three ID fields there.
#Embeddable
public class MyId {
private String partCode;
private String setCode;
private String itemCode;
}
Add needed getters & setters.
Then set in class SetItem this class to be the id like `#EmbeddedId´.
public class SetItem {
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name="partCode",
column=#Column(name="PART_CODE")),
#AttributeOverride(name="setCode",
column=#Column(name="SET_CODE"))
#AttributeOverride(name="itemCode",
column=#Column(name="ITEM_CODE"))
})
MyId id;
Check also Which annotation should I use: #IdClass or #EmbeddedId
Be sure to implement equals and hashCode in SetGroupId.
Can you provide that class?

Spring/JPA: composite Key find returns empty elements [{}]

I have build my data model using JPA and am using Hibernate's EntityManager to access the data. I am using this configuration for other classes and have had no problems.
The issue is that I created an entity with a composite primary key (the two keys are foreign keys) , adding elements works perfectly I checked it in database but I am not able to retrieve the populated row from database.
For example if I query "FROM Referentiel" to return a list of all referentiels in the table, I get this [{},{}] my list.size() has the proper number of elements (2), but the elements are null.
The entity:
#Entity
#Table(name = "Et_referentiel")
public class Referentiel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name = "id_projet")
private Projet projet;
#Id
#ManyToOne
#JoinColumn(name = "id_ressource")
private Ressource ressource;
#Column(name = "unite", nullable = false)
private String unite;
}
here is my controller getList method:
#PostMapping(value = "/list", consumes = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public List<Referentiel> listReferentiel(#RequestBody Long idProjet) {
List<Referentiel> referentiel = referentielService.listReferentiel(idProjet);
return referentiel;
}
and here is my dao methods:
#Autowired
private EntityManager em;
#Override
public void ajouterReferentiel(Referentiel ref) {
em.persist(ref);
em.flush();
}
#SuppressWarnings("unchecked")
#Override
public List<Referentiel> listReferentiel(Long idProjet) {
Query query = em.createQuery("Select r from Referentiel r where r.projet.idProjet=:arg1");
query.setParameter("arg1", idProjet);
em.flush();
List<Referentiel> resultList = query.getResultList();
return resultList;
}
Any help is greatly appreciated.
Try creating a class representing your composite key:
public class ReferentielId implements Serializable {
private static final long serialVersionUID = 0L;
private Long projet; // Same type than idProjet, same name than inside Referentiel
private Long ressource; // Same type than idRessource (I guess), same name than inside Referentiel
// Constructors, getters, setters...
}
And assign it to your entity having that composite key.
#Entity
#IdClass(ReferentielId.class) // <- here
#Table(name = "Et_referentiel")
public class Referentiel implements Serializable {
// ...
}
Notice that it is required to have a class representing your composite keys, even if that does not help in your problem.

Resources