import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/**
* This class serves as the Base class for all other DAOs - namely to hold
* common CRUD methods that they might all use. You should only need to extend
* this class when your require custom CRUD logic.
* <p>
* To register this class in your Spring context file, use the following XML.
*
* <pre>
* <bean id="fooDao" class="com.soft863.bbs.dao.hibernate.GenericDaoHibernate">
* <constructor-arg value="com.soft863.bbs.model.Foo"/>
* <property name="sessionFactory" ref="sessionFactory"/>
* </bean>
* </pre>
*
* @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a>
*/
public class GenericDaoHibernate<T, PK extends Serializable> extends
HibernateDaoSupport implements GenericDao<T, PK> {
protected final Log log = LogFactory.getLog(getClass());
private Class<T> persistentClass;
public GenericDaoHibernate() {
}
public GenericDaoHibernate(Class<T> persistentClass) {
this.persistentClass = persistentClass;
}
public void setPersistentClass(Class<T> persistentClass) {
this.persistentClass = persistentClass;
}
@SuppressWarnings("unchecked")
public List<T> getAll() {
return super.getHibernateTemplate().loadAll(this.persistentClass);
}
@SuppressWarnings("unchecked")
private T get(PK id) {
T entity = (T) super.getHibernateTemplate().get(this.persistentClass,
id);
if (entity == null) {
log.warn("Uh oh, '" + this.persistentClass + "' object with id '"
+ id + "' not found...");
throw new ObjectRetrievalFailureException(this.persistentClass, id);
}
return entity;
}
@SuppressWarnings("unchecked")
private boolean exists(PK id) {
T entity = (T) super.getHibernateTemplate().get(this.persistentClass,
id);
if (entity == null) {
return false;
} else {
return true;
}
}
private void remove(PK id) {
this.remove(this.get(id));
}
public T save(T object) {
super.getHibernateTemplate().saveOrUpdate(object);
return object;
}
private void remove(Object object) {
super.getHibernateTemplate().delete(object);
}
@SuppressWarnings("unchecked")
public Object getObject(final Class persistentClass, final String where) {
List list = this.getHibernateTemplate().executeFind(
new HibernateCallback() {
public Object doInHibernate(Session s)
throws HibernateException, SQLException {
StringBuffer sql = new StringBuffer("from "
+ persistentClass.getName() + " p ");
if (StringUtils.isNotBlank(where)) {
if (where.trim().startsWith("where ")) {
sql.append(where);
} else {
sql.append(" where ").append(where);
}
}
Query q = s.createQuery(sql.toString());
return q.list();
}
});
if (list != null) {
// 如果取到唯一一个值,返回
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 0) {
// 如果多余一个值,输出错误,返回null
// System.out.println("[warn]:getObject("+persistentClass.getName()+",\""+where+"\"):根据唯一条件得到多于一个的值,请检查!");
return null;
}
}
return null;
}
@SuppressWarnings("unchecked")
public List getObjs(final String hsql) {
return getObjs(hsql,-1,-1);
}
public List getObjs(final String hsql,final int firstResult, final int maxResult) {
List list = this.getHibernateTemplate().executeFind(
new HibernateCallback() {
public Object doInHibernate(Session s)
throws HibernateException, SQLException {
Query q = s.createQuery(hsql);
if (firstResult >= 0 && maxResult >= 0) {
q.setFirstResult(firstResult);
q.setMaxResults(maxResult);
}
return q.list();
}
});
return list;
}
public List getObjs(final String hsql, final int num) {
List list = this.getHibernateTemplate().executeFind(
new HibernateCallback() {
public Object doInHibernate(Session s)
throws HibernateException, SQLException {
Query q = s.createQuery(hsql);
if (num >= 0) {
q.setFirstResult(0);
q.setMaxResults(num);
}
return q.list();
}
});
return list;
}
public boolean exists(Class<T> persistentClass, PK id) {
synchronized (this) {
this.setPersistentClass(persistentClass);
return this.exists(id);
}
}
public T get(Class<T> persistentClass, PK id) {
synchronized (this) {
this.setPersistentClass(persistentClass);
return this.get(id);
}
}
public void remove(Class<T> persistentClass, PK id) {
synchronized (this) {
this.setPersistentClass(persistentClass);
this.remove(id);
}
}
@SuppressWarnings("unchecked")
public List getListBySql(String sql) {
SQLQuery a = this.getSession().createSQLQuery(sql);
return a.list();
}
public List getObjstBySql(final String sql, final int firstResult, final int maxResult) {
List list = this.getHibernateTemplate().executeFind(
new HibernateCallback() {
public Object doInHibernate(Session s)
throws HibernateException, SQLException {
Query q = s.createSQLQuery(sql);
if (firstResult >= 0 && maxResult >= 0) {
q.setFirstResult(firstResult);
q.setMaxResults(maxResult);
}
return q.list();
}
});
return list;
}
}
***************************分割线(下面是接口)***************************
import java.io.Serializable;
import java.util.List;
/**
* Generic DAO (Data Access Object) with common methods to CRUD POJOs.
*
* <p>Extend this interface if you want typesafe (no casting necessary) DAO's for your
* domain objects.
*
* @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a>
*/
public interface GenericDao <T, PK extends Serializable> {
public void setPersistentClass(Class<T> persistentClass);
/**
* Generic method used to get all objects of a particular type. This
* is the same as lookup up all rows in a table.
* @return List of populated objects
*/
public List<T> getAll();
/**
* Generic method to get an object based on class and identifier. An
* ObjectRetrievalFailureException Runtime Exception is thrown if
* nothing is found.
*
* @param id the identifier (primary key) of the object to get
* @return a populated object
* @see org.springframework.orm.ObjectRetrievalFailureException
*/
public T get(Class<T> persistentClass,PK id);
/**
* Checks for existence of an object of type T using the id arg.
* @param id
* @return - true if it exists, false if it doesn't
*/
public boolean exists(Class<T> persistentClass,PK id);
/**
* Generic method to save an object - handles both update and insert.
* @param object the object to save
*/
public T save(T object);
/**
* Generic method to delete an object based on class and id
* @param id the identifier (primary key) of the object to remove
*/
public void remove(Class<T> persistentClass, PK id);
/**
* Generic method to get an object based on class and identifier. An
* ObjectRetrievalFailureException Runtime Exception is thrown if nothing is
* found.
*
* @param clazz
* model class to lookup
* @param id
* the identifier (primary key) of the class
* @return a populated object
* @see org.springframework.orm.ObjectRetrievalFailureException
*/
/**
* 根据where条件,得到唯一的po对象。如果结果多于一个,返回null。并在后台输出错误。
* @param persistentClass 该po的持久化class
* @param where 查询的where条件,类似于[p.name='22']
* @return 通过查询条件得到的唯一对象
*/
public Object getObject(Class<T> persistentClass, String where);
/**
* 根据hsql语句,返回查询结果。
* @param hsql hsql语句,类似于[from com.hnjz.core.User u where u.name like 'admin%']
* @return 通过查询条件得到hibernate的查询结果(List)
*/
@SuppressWarnings("unchecked")
public List getObjs(String hsql);
public List getObjs(String hsql,final int firstResult, final int maxResult);
/**
* 返回前num个查询结果。
* @param hsql hsql语句,类似于[from com.hnjz.core.User u where u.name like 'admin%']
* @param num 查询结果数量
* @return 通过查询条件得到hibernate的查询结果(List)
*/
public List getObjs(String hsql,int num);
public List getListBySql(String sql);
public List getObjstBySql(String sql,final int firstResult, final int maxResult);
}