当前位置: 首页 > 工具软件 > Generic DAO > 使用案例 >

Generic DAO with NHibernate

百里飞捷
2023-12-01

http://geekswithblogs.net/Billy/archive/2006/02/15/69607.aspx

 

Hibernate.org has a great article on creating a generic DAO for Hibernate in Java. Below is what I use for the C# port.

 

The interface for common CRUD functionality...

 

public interface GenericDAO {

T GetById(IdDataType id, bool shouldLock);

List GetAll();

List GetByExample(T exampleInstance, string[] propertiesToExclude);

T SaveOrUpdate(T entity);

void Delete(T entity);

}

 

The generic DAO implementation...

 

public abstract class GenericNHibernateDAO : GenericDAO

{

///

Could be set using contruction injection IoC

 

public GenericNHibernateDAO(ISessionManager sessionManager) {

this.sessionManager = sessionManager;

}

 

 

public T GetById(IdDataType id, bool shouldLock) {

ISession session = GetSession();

T entity;

 

if (shouldLock) {

entity = (T) session.Load(persitentType, id, LockMode.Upgrade);

}

else {

entity = (T) session.Load(persitentType, id);

}

 

return entity;

}

 

public List GetAll() {

return GetByCriteria();

}

 

protected List GetByCriteria(params ICriterion[] criterion) {

ISession session = GetSession();

ICriteria criteria = session.CreateCriteria(persitentType);

foreach (ICriterion criterium in criterion) {

criteria.Add(criterium);

}

GenericUtils genericUtils = new GenericUtils();

return genericUtils.ConvertToGenericList(criteria.List());

}

 

public List GetByExample(T exampleInstance, string[] propertiesToExclude) {

ISession session = GetSession();

ICriteria criteria = session.CreateCriteria(persitentType);

Example example = Example.Create(exampleInstance);

 

foreach (string propertyToExclude in propertiesToExclude) {

example.ExcludeProperty(propertyToExclude);

}

 

criteria.Add(example);

 

GenericUtils genericUtils = new GenericUtils();

return genericUtils.ConvertToGenericList(criteria.List());

}

 

public T SaveOrUpdate(T entity) {

ISession session = GetSession();

session.SaveOrUpdate(entity);

 

return entity;

}

 

public void Delete(T entity) {

ISession session = GetSession();

session.Delete(entity);

}

 

private ISession GetSession() {

Check.Require(sessionManager != null, "sessionManager was not set");

return sessionManager.OpenSession();

}

 

private Type persitentType = typeof(T);

private ISessionManager sessionManager;

}

 

And for using this within your code...

 

public class ProjectDAONHibernate : GenericNHibernateDAO<Project, int> {

public ProjectDAONHibernate(ISessionManager sessionManager) : base(sessionManager) {}

}

 

 类似资料:

相关阅读

相关文章

相关问答