I was wondering if anyone could give me some tips on my data access layer \ DAOs or spot any ommisions. Im particually interested to know if i can make my DAOS static?
Firsty i have this singelton for setting up the session factory:
Code:
namespace vcf.code.framework
{
public sealed class NHibernateSessionFactory
{
private static volatile ISessionFactory instance;
private static object syncRoot = new Object();
private NHibernateSessionFactory() {}
public static ISessionFactory getFactory()
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
Configuration cfg = new Configuration();
cfg.AddAssembly("vcf");
instance = cfg.BuildSessionFactory();
}
}
}
return instance;
}
}
}
And then i have one baseDAO (fragment):
Code:
namespace vcf.code.framework
{
public class BaseDAO
{
NHibernate.ISession session = null;
NHibernate.ITransaction transaction = null;
public BaseDAO()
{
}
protected Object get(Object ob,int id)
{
try
{
ISessionFactory factory = NHibernateSessionFactory.getFactory();
session = factory.OpenSession();
return session.Get(ob.GetType(),id);
}
finally
{
if(session != null)
session.Close();
}
}
protected int add(Object o)
{
try
{
ISessionFactory factory = NHibernateSessionFactory.getFactory();
session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();
int key = Convert.ToInt32(session.Save(o));
transaction.Commit();
session.Flush();
return key;
}
catch
{
if(transaction != null)
transaction.Rollback(); // Error: we MUST roll back modifications
throw; // Here, we throw the same exception so that it is handled (printed)
}
finally
{
if(session != null)
session.Close();
}
}
protected IList find(String namedQuery,String[] Params)
{
try
{
ISessionFactory factory = NHibernateSessionFactory.getFactory();
session = factory.OpenSession();
IQuery query = session.GetNamedQuery(namedQuery);
for(int i=0;i<Params.Length;i++)
{
query.SetParameter(i,Params[i]);
}
return query.List();
}
finally
{
if(session != null)
session.Close();
}
}
I then extend this for each of my hibernate objects:
Code:
namespace vcf.code.dao
{
public class EmployerDAO : BaseDAO
{
private const string FIND_BY_NAME = "Employer.FindByName";
private const string UNVALIDATED ="Employer.Unvalidated";
public EmployerDAO()
{
}
public IList findEmployer(String name)
{
String [] array = {"%"+name+"%"};
return base.find(EmployerDAO.FIND_BY_NAME,array);
}
public int addEmployer(Employer e)
{
return base.add(e);
}
public Employer getEmployer(int i)
{
Employer e = new Employer();
return (Employer)base.get(e,i);
}