Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

This exception comes when ever any of your objects property have some invalid value i.e value that is not according to provided mapping of that object. e.g while handling optimistic concurrency if you didnt add Unsaved-value="-1" in your versin property i.e



then it leads to hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
because the requirment of version field is "-1" when in default state.

NHibernate: SqlDateTime overflow Issue on object Update

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

Yesterday i come across NHibernate SqlDateTime overflow exception when ever i update my object. During debug i all datetime fields have there default values/entered values but when i Flush my session it throws this noughty exception :)

Data.SqlTypes.SqlTypeException with the message "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.".

after alot of findings finally i found the reason behind this. Actually I didn't map that column as a Nullable OR DateTime? but just as DateTime. and when ever NHibernate read the row from DB its default value is null which NHibernate remembers. When the Object is rehydrated by NHibernate the Date is set to the value DateTime.MinValue. When the Session is synchronized with the db, NHibernate assumes that something has changed, because the currentState and the previousState are different and tries to update the row. Wich in turn fails, because DateTime.MinValue won't fit into a SqlServer datetime column.

The solution:
Make your datetime nullable either by putting ? at end of Datetime like DateTime? or Nullable<datetime>

e.g

[Property(Name = "CreatedDate", Column = "CreatedDate", NotNull = false)]//NotNull=false means null is allowed.
private DateTime? _createdDate = DateTime.Now;

I prefer using DateTime? rather then Nullable because that leades to change the date type where ever used.

Hibernate Interview questions Part 3

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

31.What is the advantage of
Hibernate over jdbc?
Hibernate Vs. JDBC :-


























JDBC Hibernate
With JDBC, developer
has to write code to map an object model's data representation to a relational
data model and its corresponding database schema.
Hibernate is flexible and powerful ORM solution to map Java classes
to database tables. Hibernate itself takes care of this mapping using XML files
so developer does not need to write code for this.
With JDBC, the automatic mapping of Java objects with database
tables and vice versa conversion is to be taken care of by the developer
manually with lines of code.
Hibernate provides transparent persistence and developer does not
need to write code explicitly to map database tables tuples to application
objects during interaction with RDBMS.
JDBC supports only native Structured Query Language (SQL).
Developer has to find out the efficient way to access database, i.e. to select
effective query from a number of queries to perform same task.
Hibernate provides a powerful query language Hibernate Query
Language (independent from type of database) that is expressed in a familiar SQL
like syntax and includes full support for polymorphic queries. Hibernate also
supports native SQL
statements
.
It also selects an effective way to perform a database manipulation task for an
application.
Application using JDBC to handle persistent data (database tables)
having database specific code in large amount. The code written to map table
data to application objects and vice versa is actually to map table fields to
object properties. As table changed or database changed then it’s essential to
change object structure as well as to change code written to map
table-to-object/object-to-table.
Hibernate provides this mapping itself. The actual mapping between
tables and application objects is done in XML files. If there is change in
Database or in any table then the only need to change XML file properties.
With JDBC, it is developer’s responsibility to handle JDBC result
set and convert it to Java objects through code to use this persistent data in
application. So with JDBC, mapping between Java objects and database tables is
done manually.
Hibernate reduces lines of code by maintaining object-table mapping
itself and returns result to application in form of Java objects. It relieves programmer
from manual handling of persistent data, hence reducing the development time and
maintenance cost.
With JDBC, caching is maintained by hand-coding. Hibernate, with Transparent Persistence, cache is set to
application work space. Relational tuples are moved to this cache as a result of
query. It improves performance if client application reads same data many times
for same write. Automatic Transparent Persistence allows the developer to
concentrate more on business logic rather than this application code.
In JDBC there is no check that always every user has updated data.
This check has to be added by the developer.
Hibernate enables developer to define version type field to
application, due to this defined field Hibernate updates version field of
database table every time relational tuple is updated in form of Java class
object to that table. So if two users retrieve same tuple and then modify it and
one user save this modified tuple to database, version is automatically updated
for this tuple by Hibernate. When other user tries to save updated tuple to
database then it does not allow saving it because this user does not have
updated data.

32.What are the Collection types in
Hibernate ?

* Bag
* Set
* List
* Array
*
Map


33.What are the ways to express joins in HQL?

HQL provides
four ways of expressing (inner and outer) joins:-

* An implicit
association join
* An ordinary join in the FROM clause
* A fetch join in
the FROM clause.
* A theta-style join in the WHERE
clause.


34.Define cascade and inverse option in one-many
mapping?

cascade - enable operations to cascade to child
entities.
cascade="allnonesave-updatedeleteall-delete-orphan"

inverse
- mark this collection as the "inverse" end of a bidirectional
association.
inverse="truefalse"
Essentially "inverse" indicates which
end of a relationship should be ignored, so when persisting a parent who has a
collection of children, should you ask the parent for its list of children, or
ask the children who the parents are?

35.What is Hibernate
proxy?

The proxy attribute enables lazy initialization of persistent
instances of the class. Hibernate will initially return CGLIB proxies which
implement the named interface. The actual persistent object will be loaded when
a method of the proxy is invoked.

36.How can Hibernate be configured to
access an instance variable directly and not through a setter method ?

By
mapping the property with access="field" in Hibernate metadata. This forces
hibernate to bypass the setter method and access the instance variable directly
while initializing a newly loaded object.

37.How can a whole class be
mapped as immutable?

Mark the class as mutable="false" (Default is
true),. This specifies that instances of the class are (not) mutable. Immutable
classes, may not be updated or deleted by the application.

38.What is the
use of dynamic-insert and dynamic-update attributes in a class
mapping?

Criteria is a simplified API for retrieving entities by
composing Criterion objects. This is a very convenient approach for
functionality like "search" screens where there is a variable number of
conditions to be placed upon the result set.

* dynamic-update (defaults
to false): Specifies that UPDATE SQL should be generated at runtime and contain
only those columns whose values have changed
* dynamic-insert (defaults to
false): Specifies that INSERT SQL should be generated at runtime and contain
only the columns whose values are not null.


39.What do you mean by
fetching strategy ?

A fetching strategy is the strategy Hibernate will
use for retrieving associated objects if the application needs to navigate the
association. Fetch strategies may be declared in the O/R mapping metadata, or
over-ridden by a particular HQL or Criteria query.

40.What is automatic
dirty checking?

Automatic dirty checking is a feature that saves us the
effort of explicitly asking Hibernate to update the database when we modify the
state of an object inside a transaction.

41.What is transactional
write-behind?

Hibernate uses a sophisticated algorithm to determine an
efficient ordering that avoids database foreign key constraint violations but is
still sufficiently predictable to the user. This feature is called transactional
write-behind.
People who read this also read:
JSP Interview
Questions
Tibco Questions
webMethods Certification
Hibernate Interview
Questions
XML Questions

42.What are Callback
interfaces?

Callback interfaces allow the application to receive a
notification when something interesting happens to an object—for example, when
an object is loaded, saved, or deleted. Hibernate applications don't need to
implement these callbacks, but they're useful for implementing certain kinds of
generic functionality.

43.What are the types of Hibernate instance states
?

Three types of instance states:

* Transient -The instance is not
associated with any persistence context
* Persistent -The instance is
associated with a persistence context
* Detached -The instance was associated
with a persistence context which has been closed – currently not
associated

44.What are the
differences between EJB 3.0 & Hibernate

Hibernate Vs EJB 3.0 :-


























Hibernate EJB 3.0
Session–Cache or collection of loaded objects relating to a
single unit of work
Persistence Context-Set of entities that can be managed by a
given EntityManager is defined by a persistence unit
XDoclet Annotations used to support Attribute Oriented
Programming
Java 5.0 Annotations used to support Attribute Oriented
Programming
Defines HQL for expressing queries to the database Defines EJB QL for expressing queries
Supports Entity Relationships through mapping files and
annotations in JavaDoc
Support Entity Relationships through Java 5.0 annotations
Provides a Persistence Manager API exposed via the Session,
Query, Criteria, and Transaction API
Provides and Entity Manager Interface for managing CRUD
operations for an Entity
Provides callback support through lifecycle, interceptor,
and validatable interfaces
Provides callback support through Entity Listener and
Callback methods
Entity Relationships are unidirectional. Bidirectional
relationships are implemented by two unidirectional relationships
Entity Relationships are bidirectional or unidirectional


45.What are the types of inheritance models in
Hibernate?

There are three types of inheritance models in
Hibernate:



  • Table per class hierarchy
  • Table per subclass
  • Table per concrete class

Hibernate Interview questions Part2

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








16.What’s
the difference between load() and get()?



load() vs. get() :-






















load()



get()



Only use the

load()

method if you are sure that the object exists.



If you are not sure that
the object exists, then use one of the


get()
methods.




load()

method will throw an exception if the unique id is not found in the
database.




get()

method will return null if the unique id is not found in the database.




load()

just returns a proxy by default and database won’t be hit until the proxy
is first invoked.




get()

will hit the database immediately.






17.What is the difference
between and merge and update ?



Use
update()
if you are sure that the session does not contain an already
persistent instance with the same identifier, and


merge()

if you want to merge your modifications at any time without consideration of the
state of the session.



19.Define cascade and inverse
option in one-many mapping?



cascade - enable operations to cascade to child entities.

cascade="allnonesave-updatedeleteall-delete-orphan"



inverse - mark this collection as the "inverse" end of a bidirectional
association.

inverse="truefalse"

Essentially "inverse" indicates which end of a relationship should be ignored,
so when persisting a parent who has a collection of children, should you ask the
parent for its list of children, or ask the children who the parents are?



20.What does it mean to be inverse?



It informs hibernate to ignore that end of the relationship. If the one–to–many
was marked as inverse, hibernate would create a child–>parent relationship (child.getParent).
If the one–to–many was marked as non–inverse then a child–>parent relationship
would be created.



23.Explain Criteria API



Criteria is a simplified API for retrieving entities by
composing Criterion objects. This is a very convenient approach for
functionality like "search" screens where there is a variable number of
conditions to be placed upon the result set.

Example :


List employees = session.createCriteria(Employee.class)

.add(Restrictions.like(
"name", "a%") )

.add(Restrictions.like(
"address", "Boston"))

.addOrder(Order.asc(
"name") )

.list();




24.Define HibernateTemplate?





org.springframework.orm.hibernate.HibernateTemplate

is a helper class which provides different methods for querying/retrieving data
from the database. It also converts checked HibernateExceptions into unchecked
DataAccessExceptions.





25.What are the benefits does
HibernateTemplate provide?



The benefits of HibernateTemplate are :





  • HibernateTemplate
    , a Spring
    Template class simplifies interactions with Hibernate Session.


  • Common functions are simplified to single
    method calls.


  • Sessions are automatically closed.


  • Exceptions are automatically caught and
    converted to runtime exceptions.



26.How do you switch between
relational databases without code changes?



Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate
appropriate hql queries based on the dialect defined.



27.If you want to see the Hibernate generated SQL statements on console, what
should we do?



In Hibernate configuration file set as follows:

true




28.What are derived properties?



The properties that are not mapped to a column, but calculated at runtime by
evaluation of an expression are called derived properties. The expression can be
defined using the formula attribute of the element.



29.What is component mapping in
Hibernate?




  • A component is an object saved as a value,
    not as a reference


  • A component can be saved directly without
    needing to declare interfaces or identifier properties


  • Required to define an empty constructor


  • Shared references not supported



Example
:



























30.What is the difference
between sorted and ordered collection in hibernate?
sorted collection
vs. order collection
:-


















sorted collection



order collection



A sorted collection is
sorting a collection by utilizing the sorting features provided by the
Java collections framework. The sorting occurs in the memory of JVM which
running Hibernate, after the data being read from database using java
comparator.



Order collection is
sorting a collection by specifying the order-by clause for sorting this
collection when retrieval.



If your collection is not
large, it will be more efficient way to sort it.



If your collection is very
large, it will be more efficient way to sort it .



Hibernate Interview questions Part 1

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

1.What is ORM ?

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

2.What does ORM consists of ?

An ORM solution consists of the followig four pieces:

* API for performing basic CRUD operations
* API to express ries refering to classes
* Facilities to specify metadata
* Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ?

The ORM levels are:

* Pure relational (stored procedure.)
* Light objects mapping (JDBC)
* Medium object mapping
* Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate?

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

5.Why do you need ORM tools like hibernate?

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

* Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
* Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
* Improved maintainability
o A lot less code to write
* Improved portability
o ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify?

Hibernate simplifies:

* Saving and retrieving your domain objects
* Making database column and table name changes
* Centralizing pre save and post retrieve logic
* Complex joins for retrieving related items
* Schema creation from object model
7.What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:



8.What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:

Programmatic configuration
XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml?
An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.



10.What are the Core interfaces are of Hibernate framework?

The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

* Session interface
* SessionFactory interface
* Configuration interface
* Transaction interface
* Query and Criteria interfaces
11.What role does the Session interface play in Hibernate?

The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();

Session interface role:

* Wraps a JDBC connection
* Factory for Transaction
* Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier


12.What role does the SessionFactory interface play in Hibernate?

The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

13.What is the general flow of Hibernate communication with RDBMS?

The general flow of Hibernate communication with RDBMS is :

* Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
* Create session factory from configuration object
* Get one session from this session factory
* Create HQL Query
* Execute query to get list containing Java objects


14.What is Hibernate Query Language (HQL)?

Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

15.How do you map Java Objects with Database tables?

* First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.
* Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example :



name="userName" not-null="true" type="java.lang.String"/>
name="userPassword" not-null="true" type="java.lang.String"/>

NHibernate: Unexpected row count: 0; expected: 1

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

here are some of my experiences when "Unexpected row count: 0; expected: 1" comes and also how can we solve them.

1. If primarykey generator has some issue e.g you in class its identity and in db its not an identity column. For those columns where your db column is not identity and its part of a requirment then "hilo" works :) for details on generator clickhere

2. Nhibernate seems to have problems when you create multiple transient entities that reference each other, and then try to save just the root entity. To avoid these problems, call
session.Save() on each transient entity after you create it, before you attach it to others else
use session.Update().

I ran into this issue today when trying to persist one of my objects. The cause of the problem was interesting. I was trying to save an object when a property/columns in the table had a unique constraint. As a result, the object that I was trying to persist would not persist simply because the object's property it failed to meet the unique constraint.

As a result, a call to Save() on the object failed and the ID on the object I was trying to save was not set, but NHibernate still processed the object and associated it with its persistence mechanism leaving it in a "semi-persistent" state with the NHibernate persistence manager (ie: NHibernate now knows about the object you tried to save and it SHOULD have fully evicted the object from its persistence manager because the save failed, but it didn't).

When an HTTP request finishes on my ASP.NET application, I flush and close all NHibernate session objects at the time the request is done. And as a result, when the HTTP request finished, NHibernate attempted to flush the jacked up "semi-persistent" object (an object who's ID was null) and ultimately generating the error above.

So, the solution that I implemented was to wrap the Save() in a try{} catch{} statement, and if the save failed, immediately close and shutdown the session, handle the error/exception. Then, check if Session.IsOpen when the HTTP request finishes.

How Hibernate / NHibernate Cascade attribute work

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

Concept 1: when ever you have a set/bag/collection of child in parent class then its attributes must be inverse = true and cascade = "all-delete-orphan".

Concept 2: In above given senario In child class the reference of ParentID should be NotNull=true and if child creates a manytoone relation with parent then its cascade=none because on child deletion or update parent should not be updated.

Concept 3: If parent have no set/bag/collection of child then in child the parent will be NotNull=false means that it can be null. This senario is required if you mark foreignkeys in child table as allow null = true. where as if you mark foreignkeys as Not null in database then its property should be NotNull=true so that child record should not be saved if its parent's foreign key contains null.

Concept 4: if your foreignkey column in database allow null and due to any constraint you dont want to change db columns and you still want that Hibernate/Nhibernate will not save the record if user didnt provide its value then 2 things need to be done.

  • Validate from frontend that the foreign key value must be given
  • In your mapping file in child class mark parent field as NotNull=true. This will enforce that value should be given to this column before save/update.

    Please comment if i am wrong

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.

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();
}
}
}
}
}