简体   繁体   English

NHibernate一直在要求LAST_INSERT_ID吗?

[英]NHibernate asking for LAST_INSERT_ID all the time?

I have a simple object: 我有一个简单的对象:

class Entity {
    public virtual int Id { get; set; }
    public virtual string Text { get; set; }
}

If I insert 10 entities using the same transaction, I get the following calls: 如果我使用相同的事务插入10个实体,则会收到以下调用:

INSERT INTO ...
SELECT LAST_INSERT_ID()

INSERT INTO ...
SELECT LAST_INSERT_ID()

...

INSERT INTO ...
SELECT LAST_INSERT_ID()

I'm not using those entities anymore, just inserting them. 我不再使用那些实体,只是将它们插入。

I saw that while using the logger to see the SQL generated when writing some complex query, and then I noticed it happens with the other tests too. 我在使用记录器查看编写某些复杂查询时生成的SQL时看到了,然后我注意到其他测试也发生了这种情况。

Is that the normal behavior? 这是正常行为吗?

This is normal if you have the primary key numbering strategy set to autoincrement. 如果将主键编号策略设置为自动递增,这是正常的。 If you use a different strategy, like low-high or another algorithmic mechanism, it won't be necessary, because NHibernate can set the ID itself. 如果您使用其他策略,例如低点或其他算法机制,则没有必要,因为NHibernate可以自行设置ID。 There's a blog post on primary key strategies, which may not be up to date on all the available Id generation mechanisms, but has the main ones covered. 一篇有关主要关键策略的博客文章 ,它可能不是最新的所有可用ID生成机制,但涵盖了主要的策略。 There's some performance and related information about the different strategies you can choose here . 您可以在此处选择的不同策略有一些性能和相关信息。 If memory serves me, using a sequence generator may be more performant on databases that support them, because Nhibernate can (at least theoretically) ask for them before using them. 如果内存对我有用,那么在支持它们的数据库上使用序列生成器可能会更有效,因为Nhibernate可以(至少在理论上)在使用它们之前要求它们。

For the mapping of your Id property to work as you'd expect, finding out what Id was just inserted is important. 为使您的Id属性映射按预期工作,找出刚刚插入的Id很重要。 Also, for mapping any associations that depend on that primary key, the ORM needs to know the primary key of the root object, so you'll likely see a round of updates on any inserted association records. 另外,对于映射依赖于该主键的任何关联,ORM需要知道根对象的主键,因此您很可能会在插入的关联记录上看到一轮更新。 (This is also the reason why one side of the association should set the Inverse property). (这也是关联的一侧应设置Inverse属性的原因)。

This is normal behavior if your key fields in your model mapping define the Generators.Identity generator. 如果您在模型映射中的关键字段定义了Generators.Identity器,则这是正常行为。

If you inspect the ID field of the model you just persisted, it will now contain the actual database value. 如果您检查刚刚保留的模型的ID字段,现在它将包含实际的数据库值。

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

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