首页 文章

使用hibernate批量saveORupdate

提问于
浏览
0

我有一个批处理操作,我必须插入或更新记录 . 我想更大的记录数量,所以我需要批量提交

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

我通常可以使用Session session = sessionFactory.openSession();事务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();

问题是hibernate在每个saveOrUpdate之前生成一个select,这似乎是一个问题 .

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

我怎样才能避免每个saveOrupdate的exta选择?

我不想使用存储过程 .

1 回答

  • 0

    以下是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无法决定要执行什么操作,则执行select .

    回到你的问题,试着给Hibernate一个提示,就像使用timestamp或version这样的字段

    Credits - Jboss HIbernate DocsStackOverFlow

相关问题