65.9K
CodeProject 正在变化。 阅读更多。
Home

在 VB.NET 中使用 Nhibernate

starIconstarIconstarIconstarIconstarIcon

5.00/5 (7投票s)

2008年1月8日

CPOL

3分钟阅读

viewsIcon

92432

在 VB.NET 中实现 Nhibernate 概念

引言

本文介绍如何在 VB.NET 中实现 Nhibernate。

背景

请参考 www.hibernate.org 了解 Nhibernate 的所有内容。我使用 VB 2005,后端使用 PostGres。

Using the Code

它需要 Nhibernate.dll 文件。从上述链接下载并安装 Nhibernate 文件,或者在 Google 中搜索。

  1. 创建一个 VB.NET 项目 - WindowsApplication1
  2. 添加一个窗体,放置 3 个标签和文本框{eno, ename, salary},1 个用于保存的按钮。
  3. 通过添加引用导入以下内容。在 WindowsApplication1 中右键单击。(现在不要更改项目的名称)。
  4. 在“添加引用”对话框中,要引用的(导入的)文件是
    • Iesi.Collections.dll
    • log4net.dll
    • Mono.Security.dll
    • Npgsql.dll --- 这是给 PostGres 用户使用的
    • Nhibernate.dll
    • System.Data.Sqlxml
  5. 在数据库中创建一个名为 testcust 的表。 {eno integer, ename varchar2(15), salary integer}。为表中的 eno 设置 Primary 键。
  6. 在项目中添加一个类文件,通过“添加新项目”。将其重命名或另存为“testcust.vb”。

    Class 文件的编码如下

    Imports NHibernate
        Imports NHibernate.Cfg
        Imports log4net
        Imports System.Configuration
    
        Public Class testcust
    
                Private enumber As Int32
                Private sal As Int32
                Private empname As String
    
            Public Overridable Property eno() As Int32
        
                Get
                        Return enumber
                End Get
    
                Set(ByVal value As Int32)
                    enumber = value
                End Set
            End Property
    
            Public Overridable Property ename() As String
                Get
                    Return empname
                End Get
        
                Set(ByVal value As String)
                    empname = value
                End Set
            End Property
    
            Public Overridable Property salary() As Int32
                Get
                    Return sal
                End Get
    
                Set(ByVal value As Int32)
                    sal = value
                End Set
            End Property
    
        End Class
  7. WindowsApplication1 中右键单击 -- “添加新项目” -- “文本文件”
  8. 将其重命名为“app.config”并按 Enter 键
  9. app.config 中,编写以下代码
    (这里用于数据库连接,我使用了 postgresql。)
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    
        <configSections>
            <section name="nhibernate"
              type="System.Configuration.NameValueSectionHandler, System, 
             Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"
        />
            <section name="log4net"
              type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"
        />
        </configSections>
    
        <log4net>
            <appender name="rollingFile" 
    		type="log4net.Appender.RollingFileAppender, log4net" >
                <param name="File" value="log.txt" />
                <param name="AppendToFile" value="true" />
                <param name="RollingStyle" value="Date" />
                <param name="DatePattern" value="yyyy.MM.dd" />
                <param name="StaticLogFileName" value="true" />
                <layout type="log4net.Layout.PatternLayout, log4net">
                    <param name="ConversionPattern" 
    		value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n" />
                </layout>
            </appender>
            <logger name ="MyApp">
                <level value="DEBUG"/>
                <appender-ref ref="rollingFile"/>
            </logger>
            <!--<root>
                <priority value="DEBUG" />
                <appender-ref ref="rollingFile" />
            </root>-->
        </log4net>
    
        
        <nhibernate>
            <add
              key="hibernate.connection.provider"          
              value="NHibernate.Connection.DriverConnectionProvider"
        />
            <add
              key="hibernate.dialect"                      
              value="NHibernate.Dialect.PostgreSQLDialect"
        />
            <add
              key="hibernate.connection.driver_class"          
              value="NHibernate.Driver.NpgsqlDriver"
        />
            <add
              key="hibernate.connection.connection_string"
              value="Server=10.3.2.1;Database=GBDEVEL;User Name=erpdotnet;Password=erp"
        />
        </nhibernate>
    
    </configuration>

    如果您使用的是 MSSQL 2000,则 app.config 的编码如下

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
            <section
              name="nhibernate" 
              type="System.Configuration.NameValueSectionHandler,System, 
    	   Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
        />
        </configSections>
    
        <nhibernate>
            <add 
              key="hibernate.connection.provider"
              value="NHibernate.Connection.DriverConnectionProvider"
        />
            <add
              key="hibernate.dialect"
              value="NHibernate.Dialect.MsSql2000Dialect"
        />
            <add
              key="hibernate.connection.driver_class"
              value="NHibernate.Driver.SqlClientDriver"
        />
            <add
              key="hibernate.connection.connection_string"
              value="Server=localhost;
    		initial catalog=nhibernate;Integrated Security=SSPI"
        />
        </nhibernate>
    </configuration>

    注意:根据您的需要更改用户名、密码、服务器名称。

  10. Form1 中,添加 3 个标签和文本框以输入 enoenamesalary 以及一个用于保存的按钮。编码如下
    Imports NHibernate
    Imports NHibernate.Cfg
    Imports log4net
    Imports System.Configuration
    Imports NHibernate.Connection
    Imports Iesi.Collections
    
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, _
    	ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim myConfig As New Configuration
            myConfig.AddAssembly("WindowsApplication1")
            myConfig.SetProperty("hibernate.dialect", _
    		"NHibernate.Dialect.PostgreSQLDialect")
    
            'Dim myFactory As ISessionFactory = myConfig.Configure.BuildSessionFactory
            Dim myFactory As ISessionFactory = myConfig.BuildSessionFactory
    
            Dim mySession As ISession = myFactory.OpenSession
    
            Dim myTransaction As ITransaction = mySession.BeginTransaction
    
            Dim cust As New testcust
            cust.eno = TextBox1.Text
            cust.ename = TextBox2.Text
            cust.salary = TextBox3.Text
    
            mySession.Save(cust)
            myTransaction.Commit()
            mySession.Close()
    
            MsgBox("success")
    
        End Sub
    End Class
  11. 与类文件一样,打开一个文本文件并将其重命名为“testcust.hbm.xml”。它的编码是
    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
        <class name="WindowsApplication1.testcust, 
    	WindowsApplication1" table="erp.testcust">
            <id name="eno" column="eno" type="Int32">
                <generator class="assigned" />
            </id>
            <property name="ename" column="ename" type="String" length="15" />
    
            <property name="salary" column="salary" type="Int32" length="12" />
        </class>
    </hibernate-mapping>

    注意:确保与数据库、类文件和此处使用的属性名称中使用的表中的数据类型保持一致。例如:在类文件或数据库中定义的 salary 必须与此处使用的名称相同。Salary 本身就是错误的。您可能会遇到 ADOException 未处理或列不匹配异常。如果使用了模式,请正确提及数据库表名。可以使用 <generator class = “assigned”><generator class = “identity”>。两者都可能产生不同的效果,具体取决于您为属性设置的约束。

  12. 确保“testcust.hbm.xml”文件的“生成操作”属性被选为“嵌入资源”(默认为“无”或“编译”)。如果未选择,您可能会遇到实体或类映射异常。
  13. 正确保存此 VB.NET 项目并运行它。
  14. 您也可以使用“hibernate.cfg.xml”代替“app.config”。它的编码是
    <?xml version='1.0' encoding='utf-8'?>
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    
        <!-- an ISessionFactory instance -->
    
        <session-factory>
    
            <!-- properties -->
    
            <property name="connection.provider">
                NHibernate.Connection.DriverConnectionProvider
    
            </property>
    
            <property name="connection.driver_class">
                NHibernate.Driver.NpgsqlDriver
    
            </property>
    
            <property name="connection.connection_string">
    		Server=10.3.2.1;Database=GBDEVEL;User Name=erpdotnet;
    		Password=erp</property>
    
            <property name="show_sql">false</property>
    
            <property name="dialect">NHibernate.Dialect.PostgreSQLDialect</property>
    
            <property name="use_outer_join">true</property>
    
            <!-- mapping files -->
    
            <mapping resource="WindowsApplication1.testcust.hbm.xml" 
    		assembly="WindowsApplication1" />
    
        </session-factory>
    
    </hibernate-configuration>

    注意:如果您使用的是 app.config,请不要编写 hibernate.cfg.xml。如果您使用它,请不要使用 app.config

  15. 对于 MSSQL2000,将此用于属性标签
      <property name="connection.provider">
    	NHibernate.Connection.DriverConnectionProvider
    </property>
    
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver
    </property>
    
    <property name="connection.connection_string">
    	Server=(local);initial catalog=AdventureWorks;User Id=sa;
    	Password=woozelwazzel</property>
    
    <property name="show_sql">false</property>
    
    <property name="dialect"> NHibernate.Dialect.MsSql2000Dialect </property>
    
    <property name="use_outer_join">true</property>

    注意:根据您的需要更改用户名、密码、服务器名称。

  16. 确保您正确导入并连接所有内容,并更改 “testcust.hbm.xml”生成操作 -- 嵌入资源属性。如果未设置,您可能会遇到 ADO 异常!!!!!
  17. 享受编码吧。

您也可以使用 VB.NET 2005。

关注点

了解一些异常发生的原因、原因以及如何解决。

历史

  • 2008 年 1 月 7 日:初始发布
© . All rights reserved.