获取HiLo号码而不调用session.Insert或session.Save

时间:2012-09-18 13:18:31

标签: c# nhibernate fluent-nhibernate

我需要使用NHibernate对SQLite数据库进行批量插入。对象的PK是HiLo int32。我尝试使用带有session.insert的NH无状态会话,它工作正常。但是,我发现使用准备好的命令更快约30-40%,所以我试图利用它。

目前我正在努力分配id(这是NH HiLo)。 我在stackoverflow(NHibernate HiLo ID Generator. Generating an ID before saving)上找到了一个解决方案 - 请参阅方法GenerateIdentifier(),但它会在每次调用时查询和更新数据库,因此这不是一个好的选择。

有什么方法可以让它按照预期工作 - 当id生成器到达竞争对手时,它只会向服务器进行1次往返以获得新的低值和高值?

public static Int64 TestNHSQLiteBulk(bool newDB)
        {
            int ProjectCount = 1000000;

            var factory = Database.CreateSQLiteSessionFactory(newDB);

            Int64 objectCount = 0;

            using (var session = factory.OpenStatelessSession())
            {
                var connection = session.Connection;
                using (var transaction = session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                {

                    // this should be removed when proper HiLo will be implemented.
                    var nextProject = session.CreateCriteria<Project>().SetProjection(Projections.Max<Project>(p => p.ProjectId)).UniqueResult();
                    int startId = (nextProject == null) ? 0 : (int)nextProject + 1;

                    var command = connection.CreateCommand();
                    command.CommandText = "Insert INTO Project (ProjectId, ProjectName) Values(?,?)";

                    var projectIdParameter = command.CreateParameter();
                    projectIdParameter.ParameterName = "ProjectId";
                    projectIdParameter.DbType = System.Data.DbType.Int32;

                    var projectNameParameter = command.CreateParameter();
                    projectNameParameter.ParameterName = "ProjectName";
                    projectNameParameter.DbType = System.Data.DbType.String;

                    command.Parameters.Add(projectIdParameter);
                    command.Parameters.Add(projectNameParameter);
                    command.Prepare();

                    for (int p = startId; p < startId + ProjectCount; p++)
                    {

                        var project = new Project()
                        {
                            ProjectName = "Project " + p
                        };

                        //found on stackoverflow, but is results a roundtrip to server on each call.
                        GenerateIdentifier(project, Database.savedConfig, session);

                        //session.Insert(project);

                        //using prepared command is almost 2x faster!
                        projectIdParameter.Value = project.ProjectId;
                        projectNameParameter.Value = project.ProjectName;
                        command.ExecuteNonQuery();

                        objectCount++;
                    }

                    transaction.Commit();
                }

            }

            return objectCount;
        }

    //this will get the value and update the hi-lo value repository in the datastore
    public static void GenerateIdentifier(object target, NHibernate.Cfg.Configuration conf, IStatelessSession session)
    {
        var targetType = target.GetType();

        var classMapping = conf.GetClassMapping(targetType);
        var impl = session.GetSessionImplementation();

        var newId = classMapping.Identifier.CreateIdentifierGenerator(impl.Factory.Dialect, classMapping.Table.Catalog, classMapping.Table.Schema,
                                                                classMapping.RootClazz).Generate(impl, target);
        classMapping.IdentifierProperty.GetSetter(targetType).Set(target, newId);
    }

1 个答案:

答案 0 :(得分:2)

您正在为每个实体创建一个新的HiLogenerator,而不是使用给定的实体。此外,生成器normqally初始化为数据库中的值,因此手动查询它是没有必要的:

public static Int64 TestNHSQLiteBulk(bool newDB)
{
    int ProjectCount = 1000000;

    var factory = Database.CreateSQLiteSessionFactory(newDB);

    var classMapping = (SingleTableEntityPersister)factory.GetClassMetadata(typeof(Project));
    var generator = classMapping.IdentifierGenerator;

    Int64 objectCount = 0;

    using (var session = factory.OpenStatelessSession())
    {
        var connection = session.Connection;
        using (var transaction = session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
        {
            var command = connection.CreateCommand();
            command.CommandText = "Insert INTO Project (ProjectId, ProjectName) Values(?,?)";

            var projectIdParameter = command.CreateParameter();
            projectIdParameter.ParameterName = "ProjectId";
            projectIdParameter.DbType = System.Data.DbType.Int32;

            var projectNameParameter = command.CreateParameter();
            projectNameParameter.ParameterName = "ProjectName";
            projectNameParameter.DbType = System.Data.DbType.String;

            command.Parameters.Add(projectIdParameter);
            command.Parameters.Add(projectNameParameter);
            command.Prepare();

            for (int p = 0; p < ProjectCount; p++)
            {
                var projectId = (long)generator.Generate(session.GetSessionImplementation(), null);

                //using prepared command is almost 2x faster!
                projectIdParameter.Value = projectId;
                projectNameParameter.Value = "Project" + projectId;
                command.ExecuteNonQuery();

                objectCount++;
            }

            transaction.Commit();
        }
    }

    return objectCount;
}