简体   繁体   English

休眠保存数据(如果数据库中不存在),否则对其进行更新

[英]Hibernate saving the data if not present in DB else updating it

I am relatively new to hibernate and looking for any mechanism where I insert new record only if the composite key is not present and else update it. 对于休眠和寻找新机制的人,我是新手,只有在复合键不存在时才插入新记录,否则将对其进行更新。

I tried with saveOrUpdate method but seems it only works for the objects in the session. 我尝试使用saveOrUpdate方法,但似乎仅适用于会话中的对象。 I want some mechanism which should query at database and if the data is present in the database already then update the record else insert it. 我想要某种机制应在数据库中查询,如果数据库中已经存在数据,则更新记录,否则将其插入。

Thanks, 谢谢,

Amandeep 阿曼迪普

As mentioned in the hibernate docs,saveOrUpdate() method should satisfy your requirement. 如休眠文档中所述,saveOrUpdate()方法应满足您的要求。 Hibernate Session doc 休眠会话文档

void saveOrUpdate(Object object) throws HibernateException Either save(Object) or update(Object) the given instance, depending upon resolution of the unsaved-value checks (see the manual for discussion of unsaved-value checking). void saveOrUpdate(Object object)抛出HibernateException save(Object)或update(Object)给定实例,具体取决于未保存值检查的分辨率(有关未保存值检查的讨论,请参见手册)。 This operation cascades to associated instances if the association is mapped with cascade="save-update". 如果关联是通过cascade =“ save-update”映射的,则此操作将级联到关联的实例。

Parameters: object - a transient or detached instance containing new or updated state 参数:object-包含新状态或更新状态的瞬态或分离的实例

Posting a sample code for your reference: In the below method a Stock object is newly inserted into the database. 发布示例代码以供参考:在以下方法中,将Stock对象新插入数据库中。

Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Stock stock = new Stock();
        stock.setStockId(70);
        stock.setStockCode("7052");
        stock.setStockName("TEST SAVE");

        StockRecord stockRecords = new StockRecord();
        stockyRecords.setDaily_record_id(80);
        stockRecords.setPriceOpen(new Float("1.2"));
        stockRecords.setPriceClose(new Float("1.1"));
        stockRecords.setPriceChange(new Float("10.0"));  

        stockRecords.setStock(stock);        
        stock.getStockRecords().add(stockRecords);

        session.save(stock);
        session.save(stockRecords);

        session.getTransaction().commit();
        session.close();

Then in another method you open a new Session and then try to insert or update a Stock object(StockId is the primary key,if you give the same id,it will update and if you give a new id,it will insert,here i have retained it as 70) 然后在另一种方法中,打开一个新的Session,然后尝试插入或更新一个Stock对象(StockId是主键,如果输入相同的ID,它将更新,如果输入新的ID,它将插入,在这里我保留为70)

public static void testSaveOrUpdate(){      
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Stock stock = new Stock();
        stock.setStockId(70);
        stock.setStockCode("7052");
        stock.setStockName("Test SaveOrUpdate");

        StockRecord stockRecords = new StockRecord();
        stockRecords.setDaily_record_id(90);
        stockRecords.setPriceOpen(new Float("1.3"));
        stockRecords.setPriceClose(new Float("1.1"));
        stockRecords.setPriceChange(new Float("10.0"));

        stockRecords.setStock(stock);        
        stock.getStockRecords().add(stockRecords);

        session.saveOrUpdate(stock);        
        session.getTransaction().commit();
    }

Just make sure that if you have a relationship to some other entity(in this case StockRecord) you give the appropriate CASCADE value.In this case,CascaseType is set to ALL. 只要确保与其他实体(在本例中为StockRecord)有关系,就可以指定适当的CASCADE值。在这种情况下,CascaseType设置为ALL。

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = false)
    @JoinColumn(name = "stockId", updatable = true, insertable = true)
    private Set<StockRecord> stockRecords = 
                            new HashSet<StockRecord>(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM