Click here to Skip to main content
15,860,972 members
Articles / Programming Languages / Visual Basic

Using Nhibernate in VB.NET

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
7 Jan 2008CPOL3 min read 87.2K   35   8
Implementation Nhibernate concept in VB.NET

Introduction

This article is about how to implement Nhibernate in VB.NET.

Background

Refer to www.hibernate.org to learn what Nhibernate is all about. I use VB 2005 with the backend as PostGres.

Using the Code

It requires Nhibernate.dll files. Download and install Nhibernate files from the above link or search for it in Google.

  1. Create a VB.NET Project - WindowsApplication1
  2. Add a form, place 3 labels and textboxes{eno, ename, salary}, 1 button for save.
  3. Import the following things by adding reference. Right Click in WindowsApplication1. (Don't change the name of the project now).
  4. In the “Add Reference” dialog box, the files to be referred(imported) are:
    • Iesi.Collections.dll
    • log4net.dll
    • Mono.Security.dll
    • Npgsql.dll --- this is for PostGres Users
    • Nhibernate.dll
    • System.Data.Sqlxml
  5. Create a table named testcust in the database. {eno integer, ename varchar2(15), salary integer}. Set Primary key for eno in the table.
  6. Add a class file in the project by “AddNew Item”. Rename or Save it as “testcust.vb”.

    CODING for the Class file is as follows:

    VB.NET
    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. Right click in the WindowsApplication1 -- “Add New Item” -- “Text File”
  8. Rename it as “app.config” and press enter
  9. In the app.config, write the code below:
    (It is here for database connection I used postgresql.)
    XML
    <?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>

    If you are using MSSQL 2000, the app.config coding is as below:

    XML
    <?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>

    Note: Change the user name, password, server name as suitable to you.

  10. In the Form1, add 3 labels and textboxes to enter eno, ename, salary and a button to save. The coding is as follows:
    VB.NET
    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. Likewise as the class file, open a text file and rename it as “testcust.hbm.xml”. The coding for this is:
    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>

    Note: Make sure with the data type used in the table in database, class file and the property name here used are case-sensitive. For example: salary defined in class file or database must have the same name here. Salary is itself wrong. You may get ADOException Unhandled or Column Mismatch Exception. Mention the database table name correctly, if you used it with schema. The <generator class = “assigned”> or <generator class = “identity”> can be used. Both may have different effects based on the constraints you set to the attributes.

  12. Make sure that “testcust.hbm.xml” file's property of Build Action is selected as Embedded Resources (default is none or compile). You may get Mapping Exception of entity or class due to this, if not selected.
  13. Save this VB.NET Project properly and Run it.
  14. You can also use “hibernate.cfg.xml” instead of “app.config”. The coding for that is:
    XML
    <?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>

    Note: If you are using app.config, don't write hibernate.cfg.xml. If you are using this, don't use app.config.

  15. For MSSQL2000, use this for the property tag:
    XML
      <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>

    Note: Change the username, password, server name as suitable for you.

  16. Make sure you import and connect everything properly and change the properties of BuildAction -- Embedded Resources of “testcust.hbm.xml”. You may get ADO EXCEPTIONS, if not!!!!!
  17. Enjoy the coding.

You can also use VB.NET 2005.

Points of Interest

Learn how some exceptions occur and why and how to solve that.

History

  • 7th January, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
_Vitor Garcia_10-May-13 4:41
_Vitor Garcia_10-May-13 4:41 
QuestionError while execute query Pin
Aarti Meswania4-Mar-13 22:10
Aarti Meswania4-Mar-13 22:10 
General5+ Pin
Aarti Meswania4-Mar-13 22:08
Aarti Meswania4-Mar-13 22:08 
GeneralMy vote of 5 Pin
Nikhil_S8-Feb-12 18:20
professionalNikhil_S8-Feb-12 18:20 
GeneralNHibernate-2.0.0 Beta1 and VB.Net in VS.Net2005 using MSSQL2005 Pin
MrBaseball348-Jul-08 10:10
MrBaseball348-Jul-08 10:10 
GeneralSimple and good. Pin
Ashutosh Phoujdar30-May-08 1:27
Ashutosh Phoujdar30-May-08 1:27 
GeneralConfiguration section Pin
FabioMaulo8-Jan-08 22:22
FabioMaulo8-Jan-08 22:22 
GeneralRe: Configuration section Pin
reloded3-May-12 7:33
reloded3-May-12 7:33 
So what is the valid config?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.