简体   繁体   English

数据库保存或单个批量保存的多个事务

[英]Multiple transactions for a database save or a single bulk save

Looking for recommendations / opinions on this one.寻找关于这个的建议/意见。 Do you think its better to save all the items in a single database transaction, or to save each item in its own transaction, the items have sub items etc... so they need to be saved in a transaction but the entire group/list does not.您认为最好将所有项目保存在单个数据库事务中,还是将每个项目保存在自己的事务中,这些项目有子项目等......所以它们需要保存在一个事务中,但整个组/列表才不是。 Almost everyone I would assume would just do a bulk save but I was curious.我认为几乎每个人都会进行批量保存,但我很好奇。 Sample pseudo code below for each.下面的示例伪代码为每个。

Single Transaction:单笔交易:

    BeginTransaction()

    for (int i = 0; i < items.Count; i++)
        items[i].Save();

    CommitTransaction()
    
    

Multiple Transactions:多笔交易:

    for (int i = 0; i < items.Count; i++)
    {
      BeginTransaction()
      items[i].Save();
      CommitTransaction() 
    }
       

This is probably determined better by the requirements of what happens when one of those transactions fails.这可能更好地取决于当其中一个事务失败时发生的情况的要求。 If the transactions are related and they should all fail, then put the transaction outside of the loop.如果交易是相关的并且它们应该失败,那么将交易放在循环之外。 If they are discrete transactions, and one failing shouldn't fail the others, put them inside the loop (and catch the failure and continue or break as appropriate).如果它们是离散事务,并且一个失败不应使其他事务失败,则将它们放入循环中(并捕获失败并酌情continuebreak )。

If that doesn't matter, and you're strictly interested in a performance perspective, transactions do add overhead.如果这无关紧要,并且您对性能方面非常感兴趣,那么事务确实会增加开销。 How much slower is a function of a great number of variables, including the individual query size and performance, database type and configuration, and hardware/virtualization resources.包含大量变量的 function 会慢多少,包括单个查询大小和性能、数据库类型和配置以及硬件/虚拟化资源。 It could be trivial/unmeasurable for slow queries (where the query itself takes the bulk of the time) or very large (for trivial queries).对于慢速查询(查询本身占用大部分时间)或非常大(对于琐碎的查询),它可能是微不足道的/不可测量的。

How much is up to you to measure.多少由你来衡量。

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

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