Member Menu
 
 Monthly JBoss newsletter:
 
Hibernate Books
CaveatEmptor

NHibernate Quick Start Guide

What is NHibernate?

NHibernate is a .NET based object persistence library for relational databases. NHibernate is a port of the excellent Java Hibernate relational persistence tool.

NHibernate handles persisting your .NET objects to and from an underlying relational database. Rather than you having to write SQL to get your objects in and out of the database, NHibernate takes care of this for you. Your code only needs to be concerned with your objects, NHibernate generates the SQL and makes sure that things end up in the correct tables and columns.

Why this guide?

Anybody who is at all familiar with Hibernate will recognize this as being really similar to Glen Smith's A Hitchhiker's Guide to Hibernate (no longer available online). The content is based on that guide so all of the credit needs to be given to him.

NHibernate's documentation is not anywhere near the point that Hibernate's documentation is. However, the projects are similar enough that the reader should be able to look at Hibernate's documentation and get a very good feel for how NHibernate works.

This doc is intended to get you up and running with NHibernate as quickly as possible. It will cover how to persist a simple object to a table. For more complex examples please see the NUnit tests that come with the code.

Translations of this guide

  • Irwan Azam has written a version of the Quick Start in Bahasa Malaysia.
  • Simone Busoli has written a version of the Quick Start in Italian.
  • Yasar Gozudeli has written a version of the Quick Start in Turkish.

First things first

You'll be needing an NHibernate distribution. Simply download the latest copy, and unzip the contents into a folder.

The development process

NHibernate is going to have some tools to help you generate a schema (in codebase now), generate classes from mapping files (on the drawing board), and to update a schema (suggestion from a new developer). However, for this example we are going to assume everything from setting up the table to coding the .NET class is done manually. Here are the steps we are going to perform:

  • Create the table to persist the .NET class to.
  • Create a .NET class that needs to be persisted.
  • Create a mapping file so NHibernate knows how to persist the .NET class' properties
  • Create a configuration file for NHibernate to know how to connect to your database
  • Use the NHibernate API

Step 1: Writing the SQL

The example we're working through is a very simple one. Consider you've developing a basic user management subsystem for your website. We'll use a Users table that looks like this (I am assuming you already have a database setup - in my case I am calling it NHibernate):

use NHibernate
go

CREATE TABLE users (
  LogonID nvarchar(20) NOT NULL default '0',
  Name nvarchar(40) default NULL,
  Password nvarchar(20) default NULL,
  EmailAddress nvarchar(40) default NULL,
  LastLogon datetime default NULL,
  PRIMARY KEY  (LogonID)
)
go

I'm using MS SQL Server 2000, but feel free to use any kind of database you've got a .NET Data Provider driver for. We've got a User table with a Logon ID, Full Name, Password, Email and date of last logon. Pretty standard sort of deal. Next step is to write a .NET Class to handle a given User

Step 2: Creating the .NET class

When we get a bunch of users in memory, we'll need some sort of object to hold them for us. NHibernate works via reflection on properties of the objects, so we'll need to add properties to the class we want to persist. A simple class that can be persisted with NHibernate looks like:

using System;

namespace NHibernate.Examples.QuickStart
{
    public class User
    {
        private string id;
        private string userName;
        private string password;
        private string emailAddress;
        private DateTime lastLogon;


        public User()
        {
        }

        public string Id 
        {
            get { return id; }
            set { id = value; }
        }

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

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

        public string EmailAddress 
        {
            get { return emailAddress; }
            set { emailAddress = value; }
        }

        public DateTime LastLogon 
        {
            get { return lastLogon; }
            set { lastLogon = value; }
        }
        
    }
}

In our example above, we've made the properties and the constructor public - but that's not a requirement for NHibernate - it can use public, protected, internal, or even private properties to persist your data.

Step 3: Writing the mapping file

So we've now got our SQL table, and the .NET class that's going to map to it. We still need a way to tell NHibernate how to map from one to the other. This is accomplished via a mapping file. The cleanest (most maintainable) way is to write one mapping file per class, and if you name it YourObject.hbm.xml and put it in the same directory as your class, NHibernate will make things even easier for you. Here's an example of what User.hbm.xml might look like:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
    <class name="NHibernate.Examples.QuickStart.User, NHibernate.Examples" table="users">
        <id name="Id" column="LogonId" type="String" length="20"> 
            <generator class="assigned" /> 
        </id> 
        <property name="UserName" column="Name" type="String" length="40"/> 
        <property name="Password" type="String" length="20"/> 
        <property name="EmailAddress" type="String" length="40"/>
        <property name="LastLogon" type="DateTime"/>
    </class>
</hibernate-mapping>

Let's have a look at some lines of interest in our file. The first tag of interest is the class tag. Here we map from the type name (class name and assembly) to the users table in our database. This is slightly different than Hibernate. You have to tell NHibernate where to load the class from. In this case we are loading the class NHibernate.Examples.QuickStart.User in the assembly NHibernate.Examples. NHibernate follows the same rules of loading a type as the .NET Framework - so if you have any confusion about how to specify the type see the .NET Framework SDK.

Let's skip the id tag for a moment and talk about the property tags. A cursory scan will show this is where the work is being done. The name attribute is the property on our .NET class, and the column is the name of the field in our database. The type attribute is optional (NHibernate will use reflection for a best-guess if you leave it out).

Ok. Let's return to that id tag. You may have guessed that this tag has something to do with mapping to the primary key of the table. You'd be right. The form of the id tag is very similar to the property tags we just looked at. We map from the Property (name) to the target database field (column).

The embedded generator tag tells NHibernate how it should produce the primary key (it's quite happy to generate one for you, of whatever type you prefer, but you'll need to tell it how). In our case, we set it to assigned, meaning that our object is going to generate its own keys (the User object will always need to have a UserID after all). If you're keen to let NHibernate generate keys for you, you'll be interested in class settings like uuid.hex and uuid.string (check out the docs for more info).

NOTE: If you are using Visual Studio .NET to compile make sure that you set the Build Action of the User.hbm.xml file to Embedded Resource. The mapping file will now be a part of the Asssembly. The subtle detail's importance will be evident later.

NOTE: If the only change you make between builds is to a mapping file then you must Rebuild the project. Visual Studio .NET will not recompile a project if only an hbm.xml file was changed.

Step 4: Creating a configuration file for your database

We still haven't told NHibernate where to find our database. The most straightforward way is to feed NHibernate a configuration section from your application's config file. This is the equivalent of using a Properties file with Hibernate. Here's what one might look like:

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

The example above uses a SqlClient driver, connects to the nhibernate database on localhost, and uses the supplied username and password. There are a bunch of other properties you can set to "tune" how NHibernate accesses your database of choice. Once again, check out the docs for detailed info.

NOTE: Please note that the above configuration file does not have any information about configuring log4net. NHibernate uses log4net to log what is happening internally. In a production application I would recommend configuring log4net and setting NHibernate to the appropriate log level for your scenario. See Configuring log4net Logging? for more details.

Step 5: Start doing magic with NHibernate

All the hard work has now been done. If all has gone well so far, you'll have the following:

  • User.cs - your C# class to persist
  • User.hbm.xml - your NHibernate mapping file
  • app.config - your configuration settings with ADO.NET connection info (you can do this in code if you like)
  • A SQL User table in your database

Making use of NHibernate in your source is pretty straightforward. The nutshell edition goes:

  • Add a reference to NHibernate.dll (in the 'bin' folder where you installed NHibernate)
  • Create a configuration object
  • Tell the configuration about the type of objects you want to store
  • Create a session to your database of choice
  • Load, save and query your objects
  • Flush() your Session back to the database

Let's have a look at some source to make it all much clearer.

To save typing, add the following using statements to the beginning of your class

using NHibernate;
using NHibernate.Cfg;

First, create a Configuration object...

The Configuration object has knowledge of all the mappings that are going on between .NET classes and the backend database.

Configuration cfg = new Configuration();
cfg.AddAssembly("NHibernate.Examples");

The Configuration object will look through the assembly for any files ending in .hbm.xml. There are other ways to add the mapping files, but this is probably the easiest.

Then, create a session object...

The ISession object represents a connection to your backend database and the ITransaction represents a NHibernate managed Transaction.

ISessionFactory factory = cfg.BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();

Then Load, Save and Query your Objects!

Now you just use your objects in a .NET-native way. Would you like to store a new User in the database? Try something like this:

User newUser = new User();
newUser.Id = "joe_cool";
newUser.UserName = "Joseph Cool";
newUser.Password = "abc123";
newUser.EmailAddress = "joe@cool.com";
newUser.LastLogon = DateTime.Now;

// Tell NHibernate that this object should be saved
session.Save(newUser);

// commit all of the changes to the DB and close the ISession
transaction.Commit();
session.Close();

As you can see, the great thing about NHibernate is the low overhead. Go ahead and query your database and verify that you see the new record in the users table. For the most part you just worry about your business objects, and tell NHibernate when you're done.

Let's say you want to retrieve an object when you know the user ID (eg. During a login process to your site). Once a session is opened it's a one-liner; pass in the key and you're done:

// open another session to retrieve the just inserted user
session = factory.OpenSession();

User joeCool = (User)session.Load(typeof(User), "joe_cool");

The User object you get back is live! Change its properties and it will get persisted to the database on next Flush().

// set Joe Cool's Last Login property
joeCool.LastLogon = DateTime.Now;

// flush the changes from the Session to the Database
session.Flush();

All you had to do to get NHibernate to write the changes you made was to ask it to Flush the Session. Go ahead and query your database through its tools to verify the Property LastLogin was updated for "joe_cool".

Even better, you can query your table and get back a System.Collections.IList of live objects. Try something like this:

IList userList = session.CreateCriteria(typeof(User)).List();
foreach(User user in userList)
{
    System.Diagnostics.Debug.WriteLine(user.Id + " last logged in at " + user.LastLogon);
}

This query will return the whole table. Typically you'll want a lot more control - like list the Users who have logged in after March 14, 2004 10:00 PM, so you'll do something like:

IList recentUsers = session.CreateCriteria(typeof(User))
                .Add(Expression.Expression.Gt("LastLogon", new DateTime(2004, 03, 14, 20, 0, 0)))
                .List();

foreach(User user in recentUsers)
{
    System.Diagnostics.Debug.WriteLine(user.Id + " last logged in at " + user.LastLogon);
}

There are a wealth of querying options in the documentation, but this will give you an idea of the kind of power Hibernate offers you.

...And finally Close() your session. This will free up the ADO.NET connection that NHibernate is using.

// tell NHibernate to close this Session
session.Close();

And that's it...

You've created objects, persisted them, and retrieved (via criteria queries and key lookup). You've gotta be happy with that!

Now that you've got a feel for NHibernate, you'll be well served by having a good look through the extensive documentation that comes with Hibernate 2.1. There's a world of cool stuff to explore like handling one-to-many SQL mapping, persisting sorted and nested collections, tuning performance and much more.

Enjoy! And happy NHibernating!

Once again - all credit should go to Glen Smith and his article that served as the template for this article - A Hitchhiker's Guide to Hibernate.

NHibernate Quick Start Guide was originally written by Mike Doerfler.


  NEW COMMENT

SqlClient driver 20 Mar 2006, 16:48 BrianSu
Where to find SqlClient driver mentioned in the sample? Thanks.
 
It is part of .NET Framework and is installed with it. 29 May 2006, 06:36 sergey
It is part of .NET Framework and is installed with it.
 
Code for this example 08 Jun 2006, 04:13 ismar
Is it possible to get the project code for this example. I can't get 
it work. Hope that is possible, beacuse I really want to get 
NHibernate work with ASP.NET. 

Thanks a lot!
 
Various issues 17 Jun 2006, 10:29 Idiosyncrasy
You may encounter a number of issues while working through the above 
quickstart; here are some tips:

(1) Don't forget to name your assembly; in Visual Studio 2005 go to 
the project menu and select <projectname> properties at the bottom of 
the menu. Here make sure the Assembly Name is equal to the one you're 
using in your .hbm.xml mapping files and specifying in your 
AddAssembly call.

(2) In both versions I tried (1.0.2.0 and 1.2.0.Alpha1) I got 
an "method get_Id() should be virtual" error. To allow dynamic proxy 
generation in your class you must add a virtual modifier to all you 
accessors, like this:

        public virtual string Id
        {
            get { return id; }
            set { id = value; }
        }

(3) If you get an "invalid column name" exception even when you're 
sure the column names are correctly spelled in the mapping file, try 
using a fully qualified name for the database table, for example:

        <class name="NHibernate.Examples.QuickStart.User, 
NHibernate.Examples" table="[NHibernate].[dbo].[Users]">
 
Re: SqlClient driver 28 Aug 2006, 13:35 vantaic
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE 
PAGE!On 20 Mar 2006 16:48, BrianSu wrote:

>Where to find SqlClient driver mentioned in the sample? Thanks.

You can find more information from the article "Databases supported by 
NHibernate"

http://www.hibernate.org/361.html 

Van
 
NHibernate configuration section 13 Sep 2006, 06:31 mrkashifali
After following the Quick Start Guide I am getting an ERROR:

The hibernate.connection.driver_class must be specified in the 
NHibernate configuration section

I have clearly declare the hibernate.connection.driver_class Key in 
app.config file:

 <add key="hibernate.connection.driver_class" 
value="NHibernate.Driver.SqlClientDriver" />

I am stucked up with this. Kindly help to solve this prob. 

Thanks, 

KK
 
Important 18 Oct 2006, 02:13 gatherer77
In Visual Studio 2005 this example works after I did that:

right-click in User.hbm.xml->Properties->Build Action="Embedded 
Resource"
 
NHibernate.MappingException: Unknown entity class: NHibernate.Us 19 Oct 2006, 13:32 rnagam1
"NHibernate.MappingException: Ukknown entity class: NHibernate.User" 
exception is thrown when trying to implement the example.

I created a windowns application named NHibernate and added the User 
class and the User.hbm.xml and the app.config.
 
If you had this problem: 05 Nov 2006, 03:03 nahuelgq
I had this fragment of code:

NHibernate.Cfg.Configuration conf = new 
NHibernate.Cfg.Configuration();

conf.AddAssembly("NHibernateTesting");

And I got this exception at the second line:
"The dialect was not set. Set the property hibernate.dialect."

The problem was that my app.config was renamed to app.config.xml, 
and that is incorrect, the file must be just "app.config". 

I hope that it has been useful.

Nahuel from Argentina.
 
Another problem that i could fix 05 Nov 2006, 03:17 nahuelgq
If you had a TypeInitializationException when you are trying to do this:

NHibernate.Cfg.Configuration conf = new NHibernate.Cfg.Configuration();

Make  sure that your app.config is well formed and is coherent with the 
nhibernate-configuration-2.0.xsd shema.

In my case, I had my config file ending like this:

<add key="hibernate.connection.connection_string"
      value="User ID=blabla;Password=blabla;Initial Catalog=blabla;Data 
Source=blabla"
    />
    <add /> <-------------- Here is the mistake
  </nhibernate>
</configuration>

The shema says that in the "add" node, the key and value attributtes are 
mandatory.
 
mapping schema 17 Nov 2006, 01:35 Beny
urn:nhibernate-mapping-2.0 should be urn:nhibernate-mapping-2.2 for 
1.2 beta
 
NHibernate Oracle SP issues 22 Nov 2006, 03:06 malar
Have you tried calling oracle sp's using NHibernate? If you have any 
samples please share it.

Can i have both input and output parameter in the stored procedure? 
I'm trying to get resultset thru refcursor using oracle sp. But it is 
not working. 

I'm using NHibernate1.2 and oracle.dataaccess.

Waiting for your feedback at the earliest.
 
hibernate.connection.driver_class Error 02 Jan 2007, 11:26 vata2999
After following the Quick Start Guide I am getting an ERROR:

The hibernate.connection.driver_class must be specified in the 
NHibernate configuration section

I have clearly declare the hibernate.connection.driver_class Key in 
app.config file:

 <add key="hibernate.connection.driver_class" 
value="NHibernate.Driver.SqlClientDriver" />

I am stucked up with this. Kindly help to solve this prob. 

Thanks, 

KK
 
Configure error 19 Jan 2007, 11:21 codemonkeyoverlord
You need to make a call to cfg.Configure. It takes in a string that is
the path to your hibernate.cfg.xml file. This "quick start" leaves a lot
to be desired. I can't get mine to load the appropriate driver, even
though it is available.
 
Re: NHibernate.MappingException: Unknown entity class: NHibernat 28 Feb 2007, 17:38 makpac
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE PAGE!
On 19 Oct 2006 13:32, rnagam1 wrote:

>"NHibernate.MappingException: Ukknown entity class: NHibernate.User"
>exception is thrown when trying to implement the example.

>I created a windowns application named NHibernate and added the User
>class and the User.hbm.xml and the app.config.

Hi,

Try to configure the .hbm.xml file's Build Action to 'Embedded Resource'
 
I got it (NHibernate 1.2 + .NET 2.0 + MS SQL Server 2000) 09 May 2007, 04:48 steinisweb
At first, i try this Quickstart Tutorial and it didn't work. So i read a
lot in forum.
Actually i change in User.hbm.xml one attribute:

old: <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
to: <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">

After i doing this i extends the table property in class tag:
old: table="users"
to: table="[NHibernate].[dbo].[users]"

because the code didn't found my table. Before i had created the
database and had executed the script from tutorial. 

Then i add virtual properties to User class. Kind of this:

public virtual string EmailAddress
{
    get { return emailAddress; }
    set { emailAddress = value; }
}

To the end. It works :-) Hopefully it helps you.
 
error on transaction.Commit() 26 Jun 2007, 13:02 mathmax
Hello,

I try to make this sample work, but I got some problems :
As steinisweb (last comment on this article) advised, I change the xmlns
attribute and make virtual all the properties of User class.
However I still got an error on : transaction.Commit();

the error message is :

could not insert: [MappingORTests.User#joe_cool][SQL: INSERT INTO
[NHibernate].[dbo].[users] (Name, Password, EmailAddress, LastLogon,
LogonId) VALUES (?, ?, ?, ?, ?)]

Have an idea of the problem ?

thank you in advance for your help.
 
MappingException received 10 Jul 2007, 02:43 frenzy776
While trying to get this quickstart to work I keep getting a 
MappingException: "XML validation error: Could not find schema 
information for the element 'urn:nhibernate-mapping-2.0:hibernate-
mapping" when calling cfg.AddAssembly("DBSandbox").

My mapping file looks like the following:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
  <class name="DBSandbox.Movies.Movie, DBSandbox" table="Movies">
    <property name="Id" type="Int32"/>
    <property name="Title" type="String" length="50"/>
    <property name="Rating" type="String" length="10"/>
    <property name="Actors" type="String"/>
  </class>
</hibernate-mapping>

Thanks in advance for any help.
 
My venture into NHibernate v1.2 and MySQL v5.0 10 Jul 2007, 05:33 MarkusS
I started reading the "NHibernate Quick Start Guide" from
http://www.hibernate.org/362.html and followed it step by step.

Unfortunately this guide is written for MS SQL Server so I had to adjust
the configuration parameters (in step 4) to those required for MySql
Server. I copied the required parameters from the article "Databases
supported by NHibernate" from http://www.hibernate.org/361.html.

For MySQL one also has to install the MySQL Connector for .NET available
at http://dev.mysql.com/downloads/connector/net/5.0.html

Add a reference to "MySql.Data" to your Visual Studio project and set
the "Copy Local" property to "True". Why that has to be done is
explained in the "NHibernate 1.2 Migration Guide" from
http://www.hibernate.org/407.html#A20

Before I executed the example code I changed the
hibernate.connection.connection_string to match my server configuration:

"Server=vm-mysql50;Database=test;User ID=root;Password=mysql;CharSet=utf8"

Make sure to set the correct CharSet or you'll get an exception later!

When I executed the example code I've run into an exception at
"cfg.AddAssembly(...)":

"NHibernateTests.User.hbm.xml(2,2): XML validation error: Could not find
schema information for the element
'urn:nhibernate-mapping-2.0:hibernate-mapping'."

After some googling I found out that since NHibernate v1.2 the
User.hbm.xml needs a little change: change the
"urn:nhibernate-mapping-2.0" to "urn:nhibernate-mapping-2.2" and the
exception should be gone!

Executing the example code again gave me another exception, this time at
"cfg.BuildSessionFactory()":

"The following types may not be used as proxies:
NHibernateTests.User: method set_Id should be virtual
NHibernateTests.User: method get_Id should be virtual"

mkay.. sounds easy. It wants the properties in the User class to be
virtual, so I made them virtual and the exception was gone.

After these "adjustments" NHibernate finally made a few rows of data
appear in my MySQL database! Have fun..!
 
Not saving object to database 19 Jul 2007, 08:09 baaziabu
I am having problem saving object to the database. When I save an 
object by invoking the save and commit method it saves it and am able 
to view however when I close the application and start it again, the 
saved details are not there. Seems to be saving in a temporary place. 

Thanks in advance
 
Re: MappingException received 28 Aug 2007, 12:50 gunwantw
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE PAGE!
On 10 Jul 2007 02:43, frenzy776 wrote:

>While trying to get this quickstart to work I keep getting a
>MappingException: "XML validation error: Could not find schema
>information for the element 'urn:nhibernate-mapping-2.0:hibernate-
>mapping" when calling cfg.AddAssembly("DBSandbox").

>My mapping file looks like the following:

><hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
>  <class name="DBSandbox.Movies.Movie, DBSandbox" table="Movies">
>    <property name="Id" type="Int32"/>
>    <property name="Title" type="String" length="50"/>
>    <property name="Rating" type="String" length="10"/>
>    <property name="Actors" type="String"/>
>  </class>
></hibernate-mapping>

>Thanks in advance for any help.

Hi,
i am getting the same exception, 
this is the code part from web.config file 
<configSections>
		<section name="hibernate-configuration" 
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
	</configSections>
	<hibernate-configuration xmlns="urn:nhibernate-configuration-
2.2">
		<session-factory>
			<property 
name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
			<property 
name="connection.provider">NHibernate.Connection.DriverConnectionProvide
r</property>
			<property 
name="connection.connection_string">
        Data Source=manik;Initial Catalog=HYBERNET;Persist Security 
Info=True;User ID=sa;Password=
      </property>
			<mapping assembly="ExampleUser"/>
		</session-factory>
	</hibernate-configuration>
Exception message is

The 'urn:nhibernate-mapping-2.2:hibernet-mapping' element is not 
declared
Thanks In advance
 
HybernetTestApp.User.hbm.xml(2,2): XML validation error: The 'ur 29 Aug 2007, 03:34 gunwantw
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE PAGE!

Hi all,

I am new to Nhybernet .

i am working on an assignment using NHibernet.
i am using a windows project for that.

here is my code component by component.

Persistence class  called User.cs.
I am having currosponding database schema for this.

using System;
using System.Collections.Generic;
using System.Text;
using NHibernate.Cfg;


namespace HybernetTestApp
{
    class User
    {
        private string id;
        private string userName;
        private string password;
        private string emailAddress;
        private DateTime lastLogon;

        public User()
        {
            //
            // TODO: Add constructor logic here
            //
                
        }




        public string Id
        {
            get { return id; }
            set { id = value; }
        }

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

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

        public string EmailAddress
        {
            get { return emailAddress; }
            set { emailAddress = value; }
        }

        public DateTime LastLogon
        {
            get { return lastLogon; }
            set { lastLogon = value; }
        }


    }
}

Mapping file for POCO class.

User.hbm.xml , build action for this is Embeded resource.
<?xml version="1.0" encoding="utf-8"?>
<hibernet-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="HybernetTestApp.User,HybernetTestApp" table="users">
    <id name="Id" column="LogonId" type="String" length="20">
      <generator class="assigned"/>
    </id>
    <property name="UserName" column="name" type="String" length="40"/>
    <property name="password" column="Password" type="String" 
ength="40"/>
    <property name="emailAddress" column="EmailAddress" tyoe="String" 
length="40"/>
    <property name="lastLogon" column="LastLogon" type="dateTime"/>

  </class>

</hibernet-mapping>


NHybernet Configuration file  nhibernet.cfg.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.DriverConnectionProvide
r</property>
    <property 
name="connection.driver_class">NHibernate.Driver.SqlClientDriver</proper
ty>
    <property name="connection.connection_string">
      Data Source=manik;Initial Catalog=HYBERNET;Persist Security 
Info=True;User ID=sa;Password=
    </property>
      <property name="show_sql">false</property>
      <property 
name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
      <property name="use_outer_join">true</property>
      <!-- mapping files -->
      <mapping resource="HybernetTestApp.User.hbm.xml" 
assembly="HybernetTestApp" />
    
    </session-factory>
</hibernate-configuration>


thats all,

now this is the SessionFactory object instantian code in from1.cs class.
ISessionFactory SessionFactory = new Configuration().Configure
( (at) "D:\DevEnv\HybernetTestApp\HybernetTestApp\hibernate (dot) cfg.xml").BuildSe
ssionFactory();


while running the project i am getting following exception :

HybernetTestApp.User.hbm.xml(3,2): XML validation error: 
The 'urn:nhibernate-mapping-2.2:hibernet-mapping' element is not 
declared.

please put a light on it 

thanks in advance
 
Re: MappingException received 30 Aug 2007, 08:35 Tatiana_V
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE PAGE!On 10 
Jul 2007 02:43, frenzy776 wrote:

>While trying to get this quickstart to work I keep getting a
>MappingException: "XML validation error: Could not find schema
>information for the element 'urn:nhibernate-mapping-2.0:hibernate-
>mapping" when calling cfg.AddAssembly("DBSandbox").


Update the XML schema reference in your hbm XML files. Change urn:nhibernate-
mapping-2.0 to urn:nhibernate-mapping-2.2 in the hibernate-mapping element.
 
Re: error on transaction.Commit() 28 Sep 2007, 05:58 SiliconDream
hello mathmax,

i have the same problem!

have you solved the problem?
inform me about the solution, please by now.

thank you
 
Re: error on transaction.Commit() 11 Oct 2007, 10:23 d-ral
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE
PAGE!On 28 Sep 2007 05:58, SiliconDream wrote:

>hello mathmax,

>i have the same problem!

>have you solved the problem?
>inform me about the solution, please by now.

>thank you

Hi!

I got kind of the same error, and it was because my record was violating
 integrity rules in my sql table? Maybe you are trying to insert an item
with the same primary key (by the way, did you remeber to set the
primary key?)
 
session.Save(newUser) 23 Oct 2007, 15:16 rhm002
Good Day

I have build this example and it works until the session.Save(newUser) 
when an exception occures. 

NHibernate.MappingException "Unknown Entry Class: User"

Code:
            Configuration cfg = new Configuration();
            cfg.AddAssembly("nhibernate");

            ISessionFactory factory = cfg.BuildSessionFactory();
            ISession session = factory.OpenSession();
            ITransaction transaction = session.BeginTransaction();

            User newUser = new User();
            newUser.Id = "joe_cool";
            newUser.UserName = "Joseph Cool";
            newUser.Password = "abc123";
            newUser.EmailAddress = "joe (at) cool (dot) com";
            newUser.LastLogon = DateTime.Now;

            session.Save(newUser);
            transaction.Commit();
            session.Close();

User.cs
using System;

public class User
{
    private string id;
    private string userName;
    private string password;
    private string emailAddress;
    private DateTime lastLogon;

    public User()
    {
    }

    public string Id
    {
        get { return id; }
        set { id = value; }
    }

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

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

    public string EmailAddress
    {
        get { return emailAddress; }
        set { emailAddress = value; }
    }

    public DateTime LastLogon
    {
        get { return lastLogon; }
        set { lastLogon = value; }
    }
}

User.hbm.xls
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
  <class name="User" table="users">
    <id name="Id" column="LogonId" type="String" length="20">
      <generator class="assigned" />
    </id>
    <property name="UserName" column="Name" type="String" length="40"/>
    <property name="Password" type="String" length="20"/>
    <property name="EmailAddress" type="String" length="40"/>
    <property name="LastLogon" type="DateTime"/>
  </class>
</hibernate-mapping>

if anyone can assist me, it would be greatly apreciated

Ronald
 
Quick Start did not work, what I did, to get it running 25 Nov 2007, 10:12 johannesbuchmann
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE PAGE!Hi,

I tried to follow this guide, but had some problems. 
VS 2005, NHibernate 1.2.0.400, MS-SQL 2005 ExpressEdition

I did the following to get it running: 
user-class:
    made all properties virtual

app-config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
        <section
            name="hibernate-configuration"
            type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"
        />
    </configSections>

   <!-- Add this element -->
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
        <session-factory xmlns="urn:nhibernate-configuration-2.2">
            <property xmlns="urn:nhibernate-configuration-2.2"
name="hibernate.dialect">NHibernate.Dialect.MsSql2005Dialect</property>
            <property xmlns="urn:nhibernate-configuration-2.2"
name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
            <property xmlns="urn:nhibernate-configuration-2.2"
name="connection.connection_string">Server=localhost\SQLEXPRESS;initial
catalog=[name of my db];Integrated Security=True</property>
            <mapping xmlns="urn:nhibernate-configuration-2.2"
assembly="NHibernate.Examples" />
        </session-factory>
    </hibernate-configuration>
</configuration>

client code:
Configuration cfg = new Configuration();
            // I added this:
            cfg.Configure();
            // instead of that: (Configure() seems to read all resources
anyway 
            // so AddAssembly() was trying to add the things twice)
            //cfg.AddAssembly("NHibernate.Examples");
            

            ISessionFactory factory = cfg.BuildSessionFactory();
            ISession session = factory.OpenSession();
            ITransaction transaction = session.BeginTransaction();

            User newUser = new User();
            newUser.Id = "joe_cool";
            newUser.UserName = "Joseph Cool";
            newUser.Password = "abc123";
            newUser.EmailAddress = "joe (at) cool (dot) com";
            newUser.LastLogon = DateTime.Now;

            // Tell NHibernate that this object should be saved
            session.Save(newUser);

            // commit all of the changes to the DB and close the ISession
            transaction.Commit();
            session.Close();

hope that makes sense and helps somehow
 
Re: NHibernate configuration section 01 Jan 2008, 14:17 wowarjuna
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE
PAGE!On 13 Sep 2006 06:31, mrkashifali wrote:

>After following the Quick Start Guide I am getting an ERROR:

>The hibernate.connection.driver_class must be specified in the
>NHibernate configuration section

>I have clearly declare the hibernate.connection.driver_class Key in
>app.config file:

> <add key="hibernate.connection.driver_class"
>value="NHibernate.Driver.SqlClientDriver" />

>I am stucked up with this. Kindly help to solve this prob.

>Thanks,

>KK

Hi

I thinks this is not the problem in the key value pair. Check the type
value of section tag. This suppose to be 

<section
      name="nhibernate" 
      type="System.Configuration.NameValueSectionHandler, System,
Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
    />

Regards,
wowarjuna
 
Re: Not saving object to database 16 Jan 2008, 16:17 lmc
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE
PAGE!On 19 Jul 2007 08:09, baaziabu wrote:

>I am having problem saving object to the database. When I save an
>object by invoking the save and commit method it saves it and am able
>to view however when I close the application and start it again, the
>saved details are not there. Seems to be saving in a temporary place.

>Thanks in advance


I'm having the same problem! I use .saveOrUpdate(). 

Could somebody answer that please? It's urgent and it will be very helpful.

Thanks for your help!
 
Re: session.Save(newUser) 22 Jan 2008, 16:55 Nandem
Dude, check this:


1: right click on hbm.xml file.
2: click in menu properties
3: check propertie "Build Action" = "Embedded Resource"
3: try compile again!

good luck!
 
Re: HybernetTestApp.User.hbm.xml(2,2): XML validation error: The 22 Jan 2008, 17:05 Nandem
HybernetTestApp.User.hbm.xml(3,2): XML validation error: 
The 'urn:nhibernate-mapping-2.2:hibernet-mapping' element is not 
declared.


this error apears that 'urn:nhibernate-mapping-2.2:hibernet-mapping'
element is not declared.

hmm

it does not exists this line should be 

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0"
assembly="assemblyName">

(or for version 1.2.1

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="assemblyName">


(i can't see others place that maybe incorrect sintax, u should look
with more attention!)

good luck!
 
Re: Not saving object to database 22 Jan 2008, 17:15 Nandem
what exactly are you guys saving ?
just one object ?

well...

there a many reasons to nHibernate not saving new instances. 

maybe are in 
try { } catch(Exception) { } 
and you cant see the error throws,

maybe (if u're using <many-to-one unique="true"> tag on hibernate, and
this object will be saved if u use property (cascade="save-update").

if in session.FlushMode is setted to FlushMode.Never
call a session.flush() before call commitTransaction (maybe it works!)


try change session.FlushMode options.


are to many reasons for it not work.
Post the code, and maybe some guy will help ya


good luck!
 
Re: Not saving object to database 15 Feb 2008, 17:46 dragos_aluculesa
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE
PAGE!On 22 Jan 2008 17:15, Nandem wrote:

>what exactly are you guys saving ?
>just one object ?

>well...

>there a many reasons to nHibernate not saving new instances.

>maybe are in
>try { } catch(Exception) { }
>and you cant see the error throws,

>maybe (if u're using <many-to-one unique="true"> tag on hibernate, and
>this object will be saved if u use property (cascade="save-update").

>if in session.FlushMode is setted to FlushMode.Never
>call a session.flush() before call commitTransaction (maybe it works!)


>try change session.FlushMode options.


>are to many reasons for it not work.
>Post the code, and maybe some guy will help ya


>good luck!

I had a situation where althrough I called session.flush() the changes
weare not in the database. after some research i found that where I cal
session.flush() then the querys are runned against the jdbc driver. Here
rezides the problem (if this could be called problem) jdbc connection
was not autocomiting. so, as a hack, I wrote this:

 public Session getSession()
    {
        if(session == null)
        {
            session = sessionFactory.openSession();
            session.setFlushMode(FlushMode.ALWAYS);
            try {
//here my connection is autocomiting
                session.connection().setAutoCommit(true);
            } catch (SQLException e) {
                LOG.error("Can't set connection autocomit");
            }
        }
        return session;
    }

But I read that your data is dissapiring when ypu restart the
application. hmmm... maybe you set         
<property name="hibernate.hbm2ddl.auto">create</property>
on startup hibernate confiruration ...
just check!
 
Please update this guide 30 May 2008, 21:21 ahug4122
POST QUESTIONS ON THE FORUM! COMMENTS HERE SHOULD ADD VALUE TO THE PAGE!
This guide is very outdated I have had to download the old version 1.2.0 
to run the examples here.

For people trying to use this quick start guide download version 1.2.0 as 
2.0.0Aplha wont work with the information supplied

Regards Ashley
 
Session.CreateCriteria(typeof(...)).List() 10 Jul 2008, 07:28 kashifpbutt
NHibernate.ICiteria crit = Session.CreateCriteria(typeof(Employee)).List
();
The List() function works like "Select * from EmployeeTable".  The 
question I have is that what type of locking is being used when 
performing this List()?  If List() applys a lock on the table before 
retrieving data, how can I set it to NOLOCK?  Any help would be greatly 
appreciated.

Kashif
 
© Copyright 2006, Red Hat Middleware, LLC. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc. [Privacy Policy]