'Why when i try to pass my int pid to my OrderDao class and problem occur?
Currently working on my OrderDao which contain insertOrder function and my Order domain have
private Products pId
public void setPId(Products pId) { this.pId = pId }
so when i try to set a pid in my OrderDao
public Orders insertOrder(int pid) {
Orders order = new Orders();
try {
manager.getTransaction().begin();
order.setPId(pid);
manager.persist(order);
manager.getTransaction().commit();
}catch (Exception e) {
e.printStackTrace();
}
return order;
}
it occur problem : int cannot be conveted to Products
its my first try on Java so is there a way to solve it?
Solution 1:[1]
public void setPId?Products pId) { this.pId = pId }
You got it wrong here, the setter is expecting a Product object but you passed an Integer instead
Solution 2:[2]
As you noted, the public void setPId?Products pId) method of "Orders" class gets a "Products" object as an argument. But you are passing an "int" number.
Replacing public void setPId?Products pId) with public void setPId?int pId) should fix the problem.
By the way, it's usually a good practice to use singular names for class names like Order and Product.
Solution 3:[3]
Assuming you have a constructor for Products that accepts its id:
order.setPId(new Products(pid));
Solution 4:[4]
As we know it's an ORM framework which implicitly understand in terms of object onlys except if you are using native query to insert productId in table. So, whenever we have entity to entity relationship we store it using object reference only.
and in this case method should be:
public void setProduct(Product product){ }
inside order class considering OneToOne mapping already done.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kei |
| Solution 2 | ParsaM |
| Solution 3 | Bohemian |
| Solution 4 | Arka Bandyopadhyay |
