普通数据访问对象,这个是Hibernate官方网站上面的一个DAO类的设计模式,基于JDK5.0范型支持,文章地址如下:http://www.hibernate.org/328.html
作者:中国IT实验室 来源:中国IT实验室 2007年8月26日
关键字:
@SuppressWarnings("unchecked")
public T findById(ID id, boolean lock)
{
T entity;
if (lock)
entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE);
else
entity = findById(id);
return entity;
}
@SuppressWarnings("unchecked")
public List findAll()
{
return findByCriteria();
}
@SuppressWarnings("unchecked")
public List findByExample(T exampleInstance)
{
Criteria crit = getSession().createCriteria(getPersistentClass());
Example example = Example.create(exampleInstance);
crit.add(example);
return crit.list();
}
@SuppressWarnings("unchecked")
public List findByExample(T exampleInstance, String[] excludeProperty)
{
Criteria crit = getSession().createCriteria(getPersistentClass());
Example example = Example.create(exampleInstance);
for (String exclude : excludeProperty)
{
example.excludeProperty(exclude);
}
crit.add(example);
return crit.list();
}
@SuppressWarnings("unchecked")
public T makePersistent(T entity)
{
getSession().saveOrUpdate(entity);
return entity;
}
public void makeTransient(T entity)
{
getSession().delete(entity);
}
@SuppressWarnings("unchecked")
protected List findByCriteria(Criterion... criterion)
{
Criteria crit = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion)
{
crit.add(c);
}
return crit.list();
}
@SuppressWarnings("unchecked")
protected List findByCriteria(Order order,Criterion... criterion)
{
Criteria crit = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion)
{
crit.add(c);
}
if(order!=null)
crit.addOrder(order);
return crit.list();
}
@SuppressWarnings("unchecked")
protected List findByCriteria(int firstResult,int rowCount,Order order,Criterion... criterion)
{
Criteria crit = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion)
{
crit.add(c);
}
if(order!=null)
crit.addOrder(order);
crit.setFirstResult(firstResult);
crit.setMaxResults(rowCount);
return crit.list();
}
}