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.
- Create a VB.NET Project -
WindowsApplication1
- Add a form, place 3 labels and textboxes{
eno
, ename
, salary
}, 1 button for save. - Import the following things by adding reference. Right Click in
WindowsApplication1
. (Don't change the name of the project now). - 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
- Create a table named
testcust
in the database. {eno integer
, ename varchar2(15)
, salary integer
}. Set Primary
key for eno
in the table. - 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:
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
- Right click in the
WindowsApplication1
-- “Add New Item” -- “Text File” - Rename it as “app.config” and press enter
- In the app.config, write the code below:
(It is here for database connection I used postgresql.)
="1.0"="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] <%X{auth}> - %m%n" />
</layout>
</appender>
<logger name ="MyApp">
<level value="DEBUG"/>
<appender-ref ref="rollingFile"/>
</logger>
</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:
="1.0"="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.
- In the
Form1
, add 3 labels and textboxes to enter eno
, ename
, salary
and a button to save. The coding is as follows:
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.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
- Likewise as the class file, open a text file and rename it as “testcust.hbm.xml”. The coding for this is:
="1.0"="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.
- 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.
- Save this VB.NET Project properly and Run it.
- You can also use “hibernate.cfg.xml” instead of “app.config”. The coding for that is:
='1.0'='utf-8'
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<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 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.
- For MSSQL2000, use this for the property tag:
<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.
- 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!!!!!
- 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
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.