【问题标题】:Update an existing entry with auto increment in Hibernate在 Hibernate 中使用自动增量更新现有条目
【发布时间】:2016-02-25 04:23:40
【问题描述】:

我有一个使用 Hibernate 映射到数据库表的价格类。是这样的:

Price {
    long priceID; //auto increment, Primary key
    long itemID;  // Foreign key, each price corresponds to a unique Item
    double price; // actual price
}

我想要的是在保存具有现有 itemID 的价格对象时,它会使用相同的 itemID 更新 db 中现有条目的价格。

但它最终创建了一个具有相同 itemID 的重复条目。

如何避免重复条目并更新现有条目?

【问题讨论】:

    标签: hibernate duplicates unique


    【解决方案1】:

    您可以实现如下所示:

    引入一个方法来检查数据库中是否已经存在Item:

    // 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;
    }
    

    如果商品已经在数据库中,您可以更新现有商品的价格:

        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 {
            session.beginTransaction();
            Item item = new Item(item_name);
            Price price = new Price(item, newPrice);
            session.save(price);
            session.getTransaction().commit();
        }
    

    更新:
    项目实体类:-

    public class Item implements java.io.Serializable {
    
    private Integer itemId;
    private String itemName;
    private Set<Price> prices = new HashSet<>();
    ...
    

    价格实体类:-

     public class Price  implements java.io.Serializable {
    
     private Integer priceId;
     private Item item;
     private double price;
     ...
    

    【讨论】:

    • 我最终检查了它是否是现有记录。如果是,则调用更新,否则调用保存。就像你说的那样。
    猜你喜欢
    • 2011-09-13
    • 2019-03-04
    • 2021-05-10
    • 2012-03-18
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多