views:

104

answers:

4

I'm new to NHibernate, so this is a basic question..

When fetching data from the database through an NHibernate session I've only done it using the Id this far, e.g. like this:

var customer = Session.Get<Customer>(customerId); 

But how do I fetch an object based on a property that isn't the Id? E.g. fetch a customer by search on the Name property. This could return 0-n answers, so I'm assuming I would get a list back?

+2  A: 

Using HQL it would look something like:

session.CreateQuery("from Customer where Name=:name")
       .SetString("name", name)
       .List<Customer>();
nullptr
Thanks! Works perfectly, and HQL looks quite nice - is it?
stiank81
+2  A: 

You basically have two options here: HQL and the Criteria API. The Hibernate documentation is fantastic, so I strongly suggest you read it rather than having me post an unnecessarily verbose answer.

jcm
Thanks! The Criteria API looks interesting too. Will have a closer look at it.
stiank81
Even more; i prefer the Criteria API over HQL. :)
Frederik Gheysels
+4  A: 

Another option - Linq2NHibernate which is getting more and more mature lately.

usage looks like this=>

var employees = Session.Linq<Employee>()
    .Single(employee=>employee.Name==name);

Linq extension method returns INHibernateQueryable interface which implements IQueryable.

Arnis L.
I think I'd hold out until NH3 for this. It's still maturing.
jcm
Okay - this looks very interesting! At the moment I'm suffering of overload of new frameworks and technologies to learn, so I can't take another one right now. But thanks; Linq2NHibernate is noted, and I will definitely have a closer look later on!
stiank81
Another linq provider is NHibernate.Linq. It's more limited than the 3.0 provider, but the limited functionality is pretty stable.
Paco
Actually - i've already used this on real project. Works quite nice. And linq2nhibernate is not mutually exclusive with hql/icriteria.
Arnis L.
+2  A: 

There are many ways of querying NHibernate:

  • HQL
  • Criteria
  • Query by example
  • Query over criteria
  • LINQ (2 different linq providers available)
  • H-SQL
  • SQL
  • You can implement your own way of querying
Paco
Thanks for this rich list! What's your personal preference?
stiank81
Depending how complicated the query is, I use the following: 1.beta linq, 2.old linq 3.hql 4.hsql 5.sql. I have used criteria in the past, but it's to error prone and compared to linq. The beta linq is usable as long as you write tests for your queries and use other query methods for the exceptional cases.
Paco