运行环境:VS2008
1)使用IStatelessSession, 设置hibernate.cfg.xml中:<property name="adonet.batch_size">250</property>.
2) 如果不想忍受调试时导入的慢速度,设置<property name="show_sql">false</property>>(此配置用于调试时在控制台输出sql script,检查错误,但是会使导入变成龟速)。
3)代码如下:
3.1)创建Session:
public class Common
{
/// <summary>
/// Init a open Stateless session, caller needs to close this session manually.
/// <para>It used to commit a lot of data in a transaction</para>
/// </summary>
public static IStatelessSession StatelessSession
{
get
{
lock (thisLock)
{
if (sessionFactory == null)
{
Configuration cfg = new Configuration();
sessionFactory = cfg.Configure().BuildSessionFactory();
}
IStatelessSession session = null;
try
{
session = sessionFactory.OpenStatelessSession();
return session;
}
catch
{
return null;
}
}
}
}
private static ISessionFactory sessionFactory;
private static readonly object thisLock = new object();
}
}
3.2) 批量保存:
public static bool save(List<object> objs, out string msg)
{
IStatelessSession session = Common.StatelessSession;
bool _result = false;
msg = "";
if (session == null)
return false;
using (session)
{
using (ITransaction tran = session.BeginTransaction())
{
try
{
foreach (var _item in objs)
{
session.Insert(_item);
}
tran.Commit();
_result = true;
}
catch (Exception ex)
{
tran.Rollback();
msg = ex.Message + "--" + ex.InnerException;
}
}
}
return _result;
}