I have a class Price mapped to a db table using Hibernate. It's like this:
Price {
long priceID; //auto increment, Primary key
long itemID; // Foreign key, each price corresponds to a unique Item
double price; // actual price
}
What I want is when saving a price object with an existing itemID, it updates the price of the existing entry in db with the same itemID.
But it ended up creating a duplicate entry with the same itemID.
What can I do to avoid duplicate entry and update the existing entry?
You can implement something like below :
Introduce a method to check if Item is already exist in the DB:
// Session session= ...
public Map<Integer, Item> getItemIfExist(String item_name) {
Map<Integer, Item> returnMap = new HashMap<>();
Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.eq("itemName", item_name));
List<Item> items = cr.list();
for (Item item : items) {
Set<Price> price = item.getPrices();
for (Price p : price) {
returnMap.put(p.getPriceId(), item);
}
}
return returnMap;
}
If item is already in the DB you can update the price of the existing item:
String item_name = "Water";//this may vary according to your requirement
double newPrice = 4.50;//as well as the price
if (!checkItemIfExist(item_name).isEmpty()) {
for (Map.Entry<Integer, Item> entry : checkItemIfExist(item_name).entrySet()) {
int priceId = entry.getKey();
Item item = entry.getValue();
session.beginTransaction();
Price price = (Price) session.load(Price.class, priceId);
price.setItem(item);
price.setPrice(newPrice);
session.update(price);
session.getTransaction().commit();
}}
Else you can save it as an new item to the DB:
else {
session.beginTransaction();
Item item = new Item(item_name);
Price price = new Price(item, newPrice);
session.save(price);
session.getTransaction().commit();
}
Update :
Item Entity class :-
public class Item implements java.io.Serializable {
private Integer itemId;
private String itemName;
private Set<Price> prices = new HashSet<>();
...
Price Entity class :-
public class Price implements java.io.Serializable {
private Integer priceId;
private Item item;
private double price;
...