承接基于.Net的系统研发,精通物流系统,特别是仓储物流管理,有意者请联系。

NHibernate示例

第一步:创建数据库
创建表:users
LoginID varchar 50 
UserName varchar 50 
Password varchar 50 

第二步:创建实体(可以利用工具生成)
在Entity.csproj中添加User.cs文件

namespace Entity
{
    public class User
    {
        private string loginID;
        private string userName;
        private string password;

        public virtual string LoginID
        {
            get { return loginID; }
            set { loginID = value; }
        }

        public virtual string UserName
        {
            get { return userName; }
            set { userName = value; }
        }

        public virtual string Password
        {
            get { return password; }
            set { password = value; }
        }
    }
}

创建实体映射文件User.hbm.xml(此文件必须是嵌入式资源)
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
  <class name="Entity.User,Entity" table="Users">
    <id name="LoginID" column="LoginID" type="String"  unsaved-value="">
      <generator class="assigned" />
    </id>
    <property name="UserName" column="UserName" type="String" />
    <property name="Password" column="Password" type="String" /> 
  </class>
</hibernate-mapping>


第三步:客户端创建hibernate.cfg.xml配置文件
<?xml version="1.0" encoding="utf-8" ?>
  <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.0" >
    <session-factory name="NH">
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>     
      <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
      <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
      <property name="connection.connection_string">Server=localhost;initial catalog=systemframework;uid=sa;pwd=</property>
      </session-factory>
    </hibernate-configuration>

第四步:客户端调用
Configuration cfg = new Configuration().Configure();
            cfg.AddAssembly("Entity");
            ISessionFactory factory = cfg.BuildSessionFactory();
            ISession session = factory.OpenSession();
            ITransaction trans = session.BeginTransaction();           
            Entity.User user = new Entity.User ();
            user.LoginID = "2";
            user.UserName = "test";
            user.Password = "test";
           
            try
            {
                session.Save(user);
                trans.Commit();
            }
            catch(Exception ex)
            {
                trans.Rollback();
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

            数据库中新插入LoginID是2的用户,保存成功。

            终于得到想要的结果了,感觉很开心,这是成功的一半。(2007年9月29日 星期六 19:38:50)

posted @ 2007-09-29 19:33  阿修罗一平  阅读(237)  评论(0编辑  收藏  举报