【问题标题】:batch saveORupdate using hibernate使用休眠批量保存或更新
【发布时间】:2014-06-10 03:09:39
【问题描述】:

我有一个批处理操作,我必须插入或更新记录。我想插入更多的记录,所以我需要一个接一个地提交一个批


1)如果是新的则插入
2)如果存在则更新。


我通常可以使用

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
  Customer customer = new Customer(.....);
  session.saveOrUpdat(customer);
  if ( i % 20 == 0 ) { //20, same as the JDBC batch size
    //flush a batch of inserts and release memory:
    session.flush();
    session.clear();
  }
}

tx.commit();
session.close();

问题是休眠在每个 saveOrUpdate 之前生成一个选择,这似乎是一个问题。

对象的primarykey总是在传递给hibernate之前填充。因为它的primaryKey永远不会由hibernate使用sequencer或其他任何东西生成。

我怎样才能避免每次保存或更新的这种额外选择?

我不想使用存储过程。

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    以下是 Hibernate 决定是更新还是将记录插入数据库所需的步骤。

    saveOrUpdate() does the following:
    
    if the object is already persistent in this session, do nothing
    if another object associated with the session has the same identifier, throw an exception
    if the object has no identifier property, save() it
    if the object's identifier has the value assigned to a newly instantiated object, save() it
    if the object is versioned by a <version> or <timestamp>, and the version property value is the same value assigned to a newly instantiated object, save() it
    otherwise update() the object.
    

    如果在任何情况下发生冲突并且休眠无法决定执行什么操作,它会进行选择。

    针对您的问题,尝试向 Hibernate 提供提示,例如使用时间戳或版本等字段

    学分 - Jboss HIbernate Docs, StackOverFlow

    【讨论】:

    • 感谢您的回答。但它不回答我的问题。我如何防止休眠发出额外的选择。在我的情况下,具有相同 ID 的对象可能或可能已经存在于 DB 中(不在会话中)。所以hibernate首先通过使用该select语句检查是否已经存在具有该id的对象。我想避免这种情况。如何?
    • 创建一个字段并在您的实体中使用版本对其进行注释,并为该特定表创建一个名为版本的列。如果版本设置为默认值,则保存,否则更新!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 2011-12-04
    • 2012-01-18
    • 2011-09-20
    • 2018-09-29
    • 1970-01-01
    • 2013-06-09
    相关资源
    最近更新 更多