Understanding NHibernate <generator> element

Posted by Zafar Ullah - zafarjcp@gmail.com | 11:35 AM | , , , | 1 comments »

Every database supports mechanism to define primary keys and numeric sequence generator. so being and Data Access Layer NHibernate also provide mechanism to handle primary keys and numeric sequence generator.

Before moving to NHibernate numeric sequence generator element, here is a brief description of Primary key and numeric sequence generator(Identity).

Note: Query uses TSQL (Microsoft SQL Server) as its scripting language.

What is Primary Key
A primary key is a table column that serves a special purpose. Each database table needs a primary key because it ensures row-level accessibility. If you choose an appropriate primary key, you can specify a primary key value, which lets you query each table row individually and modify each row without altering other rows in the same table. The values that compose a primary key column are unique; no two values are the same. Each table has one and only one primary key, which can consist of one or many columns.

What is Identity Column

"An identity column creates a numeric sequence for you". You can specify a column as an identity in the CREATE TABLE statement:

CREATE TABLE dbo.Tasks ( TaskId int identity(1,1), TaskDesc varchar(200) )
The identity clause specifies that the column TaskId is going to be an identity column. The first record added will automatically be assigned a value of 1 (the seed) and each subsequent record will be assigned a value 1 higher (the increment) than the previous inserted row.

This is how Microsoft SQL Sever provides the mechanism to generate numeric ids in a sequence.

Now coming towards NHibernate which not only provide configuration mechanism to use existing sqlserver functionality but also provide its own generator mechanism.

Primary Key
Mapped classes must declare the primary key column of the database table. Most classes will also have a property holding the unique identifier of an instance. The <id> element defines the mapping from that property to the primary key column.
<id
name="PropertyName" (1)
type="typename" (2)
column="column_name" (3)
unsaved-value="anynonenullid_value" (4)
access="fieldpropertynosetterClassName(5)">

<generator class="generatorClass"/>
</id>
(1)
name (optional): The name of the identifier property.
(2)
type (optional): A name that indicates the NHibernate type.
(3)
column (optional - defaults to the property name): The name of the primary key column.
(4)
unsaved-value (optional - defaults to a "sensible" value): An identifier property value that indicates that an instance is newly instantiated (unsaved), distinguishing it from transient instances that were saved or loaded in a previous session.
(5)
access (optional - defaults to property): The strategy NHibernate should use for accessing the property value.
If the name attribute is missing, it is assumed that the class has no identifier property.
The unsaved-value attribute is almost never needed in NHibernate 1.0.
There is an alternative <composite-id> declaration to allow access to legacy data with composite keys. We strongly discourage its use for anything else.

1. generator

The required <generator> child element names a .NET class used to generate unique identifiers for instances of the persistent class. If any parameters are required to configure or initialize the generator instance, they are passed using the <param> element.
<id name="Id" type="Int64" column="uid" unsaved-value="0">
<generator class="NHibernate.Id.TableHiLoGenerator">
<param name="table">uid_table</param>
<param name="column">next_hi_value_column</param>
</generator>
</id>
All generators implement the interface NHibernate.Id.IIdentifierGenerator. This is a very simple interface; some applications may choose to provide their own specialized implementations. However, NHibernate provides a range of built-in implementations. There are shortcut names for the built-in generators:
increment
generates identifiers of type Int64, Int16 or Int32 that are unique only when no other process is inserting data into the same table. Do not use in a cluster.
identity
supports identity columns in DB2, MySQL, MS SQL Server and Sybase. The identifier returned by the database is converted to the property type using Convert.ChangeType. Any integral property type is thus supported.
sequence
uses a sequence in DB2, PostgreSQL, Oracle or a generator in Firebird. The identifier returned by the database is converted to the property type using Convert.ChangeType. Any integral property type is thus supported.
hilo
uses a hi/lo algorithm to efficiently generate identifiers of type Int16, Int32 or Int64, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with a user-supplied connection.
seqhilo
uses a hi/lo algorithm to efficiently generate identifiers of type Int16, Int32 or Int64, given a named database sequence.
uuid.hex
uses System.Guid and its ToString(string format) method to generate identifiers of type string. The length of the string returned depends on the configured format.
uuid.string
uses a new System.Guid to create a byte[] that is converted to a string.
guid
uses a new System.Guid as the identifier.
guid.comb
uses the algorithm to generate a new System.Guid described by Jimmy Nilsson in the article http://www.informit.com/articles/article.asp?p=25862.
native
picks identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned
lets the application to assign an identifier to the object before Save() is called.
foreign
uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key association.

1.1. Hi/Lo Algorithm

The hilo and seqhilo generators provide two alternate implementations of the hi/lo algorithm, a favorite approach to identifier generation. The first implementation requires a "special" database table to hold the next available "hi" value. The second uses an Oracle-style sequence (where supported).
<id name="Id" type="Int64" column="cat_id">
<generator class="hilo">
<param name="table">hi_value</param>
<param name="column">next_value</param>
<param name="max_lo">100</param>
</generator>
</id>
<id name="Id" type="Int64" column="cat_id">
<generator class="seqhilo">
<param name="sequence">hi_value</param>
<param name="max_lo">100</param>
</generator>
</id>
Unfortunately, you can't use hilo when supplying your own IDbConnection to NHibernate. NHibernate must be able to fetch the "hi" value in a new transaction.

1.2. UUID Hex Algorithm

<id name="Id" type="String" column="cat_id">
<generator class="uuid.hex">
<param name="format">format_value</param>
<param name="seperator">seperator_value</param>
</generator>
</id>
The UUID is generated by calling Guid.NewGuid().ToString(format). The valid values for format are described in the MSDN documentation. The default seperator is - and should rarely be modified. The format determines if the configured seperator can replace the default seperator used by the format.

1.3. UUID String Algorithm

The UUID is generated by calling Guid.NewGuid().ToByteArray() and then converting the byte[] into a char[]. The char[] is returned as a String consisting of 16 characters.

1.3. GUID Algorithms

The guid identifier is generated by calling Guid.NewGuid(). To address some of the performance concerns with using Guids as primary keys, foreign keys, and as part of indexes with MS SQL the guid.comb can be used. The benefit of using the guid.comb with other databases that support GUIDs has not been measured.

1.4. Identity columns and Sequences

For databases which support identity columns (DB2, MySQL, Sybase, MS SQL), you may use identity key generation. For databases that support sequences (DB2, Oracle, PostgreSQL, Interbase, McKoi, SAP DB) you may use sequence style key generation. Both these strategies require two SQL queries to insert a new object.
<id name="Id" type="Int64" column="uid">
<generator class="sequence">
<param name="sequence">uid_sequence</param>
</generator>
</id>
<id name="Id" type="Int64" column="uid" unsaved-value="0">
<generator class="identity"/>
</id>
For cross-platform development, the native strategy will choose from the identity, sequence and hilo strategies, dependent upon the capabilities of the underlying database.

1.5. Assigned Identifiers

If you want the application to assign identifiers (as opposed to having NHibernate generate them), you may use the assigned generator. This special generator will use the identifier value already assigned to the object's identifier property. Be very careful when using this feature to assign keys with business meaning (almost always a terrible design decision).
Due to its inherent nature, entities that use this generator cannot be saved via the ISession's SaveOrUpdate() method. Instead you have to explicitly specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession.

When you try to connect to an instance of Microsoft SQL Server 2005 from a remote computer, you may receive an error message. This problem may occur when you use any program to connect to SQL Server. For example, you receive the following error message when you use the SQLCMD utility to connect to SQL Server:

Sqlcmd: Error: Microsoft SQL Native Client: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.

This problem may occur when SQL Server 2005 is not configured to accept remote connections. By default, SQL Server 2005 Express Edition and SQL Server 2005 Developer Edition do not allow remote connections. To configure SQL Server 2005 to allow remote connections, complete all the following steps:

Enable remote connections on the instance of SQL Server that you want to connect to from a remote computer.
Turn on the SQL Server Browser service.
Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.


Follow the following link for more detail by microsoft support

http://support.microsoft.com/kb/914277

Some time same error occur because of your configuration in web.config.

if your error is some thing like

"An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connection. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"

Cause: ASP.Net 2.0 Providers are trying to pull from the server's (nonexistent) Providers database.
By default the machine.config file is trying to pull the Provider information from a SQLExpress database using an invalid connection string named "LocalSQLServer". Many web servers will not have SQLExpress enabled, and will not have this value set to a valid SQL Server database that is of use to you. In a shared hosting environment, this is especially true, as it would be expected that you would want your Provider information stored in your database and not some single database shared by the other users of that web server.

Fix:
Since you probably cannot access the machine.config file, you need to override the Provider settings in your web.config file, and set the connection string name to your connection string name. The following code comes from the machine.config file and has been modified to first remove each provider before adding the provider.

Add the following code to your web.config file just under the "" tag.
Make sure to replace the 3 occurrences of connectionStringName="LocalSQLServer" with your connection string name.

This goes in the system.web section of web.config.



















Your database must be configured for the ASP.Net 2.0 Providers. This article assumes that you have already configured your database to use ASP.Net 2.0 Providers. If you haven't, there is an article at http://www.aquesthosting.com/HowTo/Sql2005/Providers.aspx.

NHibernate Presentations

Posted by Zafar Ullah - zafarjcp@gmail.com | 7:41 AM | , , , , , | 0 comments »

Here are some of very importatn/impressive NHibernate presentation for biggners and advance level NHibernate developers.

To start working with NHibernate you have to download its reference documentation first.


The Basics for NHibernate

Quering with NHibernate

Associating with NHibernate

NHibernate Advance Topics

NHibernate Performance

Object Relational Mapping - NHibernate & Active Record

NHibernate Exercises (for 1.0.2)

Using Castle Active Record

All the above given topics are open for your valuable comments :)

Generic List for NHibernate

Posted by Zafar Ullah - zafarjcp@gmail.com | 8:24 AM | , , , , , , | 0 comments »

A Generic method that takes GenericList as an argument and fill it with the data of type you pass as . Converts a non-typed collection into a strongly typed collection. This will fail if
the non-typed collection contains anything that cannot be casted to type of T.

The sample method uses CSLA framework with Database layer as NHibernate.
You can get CSLA from http://www.lhotka.net/ where as its NHibernate addon is available at http://www.codeplex.com/ under CSLA Contributions.

Here's the code you are looking for


public static void FillList(out List list)
{
list = null;
// Get an NHibernate session factory where DatabaseKey = connectionstring
ISessionFactory sessionFactory = Csla.NHibernate.Cfg.GetSessionFactory(DatabaseKey);

// Open an NHibernate session from the factory
using (ISession session = sessionFactory.OpenSession())
{
// Begin a transaction on the session
using (ITransaction transaction = session.BeginTransaction())
{
try
{

System.Collections.IList listOfObjects = session.CreateCriteria(typeof(T)).List();
T[] temp = new T[listOfObjects.Count];
listOfObjects.CopyTo(temp, 0);
list = new List(temp);
}
catch (HibernateException)
{
if (null != transaction)
{
transaction.Rollback();
}
}
}
}
}