我的hibernate底层封装,hibernate底层封装,我的hibernate底
分享于 点击 21297 次 点评:215
我的hibernate底层封装,hibernate底层封装,我的hibernate底
我的hibernate底层封装,来抽象这个hibernate底层抽象封装说明一下:1.ExtendedHibernateDaoSupport主要数据层有读写分离,所以这个类就是起这样一个作用2.BaseDAOHibernate 是这个底层抽象封装精华了。还是大家去看代码吧。呵呵。
[Java]代码
import java.io.Serializable;import java.sql.SQLException;import java.util.List;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.hibernate.Criteria;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.SQLQuery;import org.hibernate.Session;import org.hibernate.type.Type;import org.springframework.dao.DataAccessException;import org.springframework.orm.ObjectRetrievalFailureException;import org.springframework.orm.hibernate3.HibernateCallback;import org.springframework.orm.hibernate3.HibernateTemplate;import com.net365.core.dao.DAO;import com.net365.core.search.Result;/** * This class serves as the Base class for all other DAOs - namely to hold * common methods that they might all use. Can be used for standard CRUD * operations.</p> * * <p><a href="BaseDAOHibernate.java.html"><i>View Source</i></a></p> * * @author <a href="mailto:songfu.zhang@gmail.com">Zhang Songfu</a> */public class BaseDAOHibernate extends ExtendedHibernateDaoSupport implements DAO { protected final Log log = LogFactory.getLog(getClass()); /** * @see com.net365.core.dao.DAO#saveObject(java.lang.Object) */ public void saveObject(Object o) { getHibernateTemplate().saveOrUpdate(o); } /** * @see com.net365.core.dao.DAO#getObject(java.lang.Class, java.io.Serializable) */ public Object getObject(Class clazz, Serializable id) { Object o = getHibernateTemplate().get(clazz, id); if (o == null) { throw new ObjectRetrievalFailureException(clazz, id); } return o; } /** * @see com.net365.core.dao.DAO#getObjects(java.lang.Class) */ public List getObjects(Class clazz) { return getHibernateTemplate().loadAll(clazz); } /** * @see com.net365.core.dao.DAO#removeObject(java.lang.Class, java.io.Serializable) */ public void removeObject(Class clazz, Serializable id) { getHibernateTemplate().delete(getObject(clazz, id)); } /* (non-Javadoc) * @see com.net365.core.dao.DAO#removeObject(java.lang.Object) */ public void removeObject(Object o) { getHibernateTemplate().delete(o); } //~ Convenience find methods ============================================ protected List findByCriteria(final CriteriaBuilder criteriaBuilder) { return findByCriteria(criteriaBuilder, -1, -1).getData(); } protected Result findByCriteria(final CriteriaBuilder criteriaBuilder, final int start, final int limit) { return (Result) getReadOnlyHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Criteria criteria = null; int count = -1; if (start != -1 && limit != -1) { criteria = criteriaBuilder.buildCountCriteria(session); if (criteria != null) { count = ((Integer) criteria.list().iterator().next()).intValue(); } } criteria = criteriaBuilder.buildCriteria(session); if (start >= 0) { criteria.setFirstResult(start); } if (limit >= 0) { criteria.setMaxResults(limit + 1); } List data = criteria.list(); Result result = new Result(start, limit); result.setTotal(count == -1 ? data.size() : count); result.setData(data); return result; } }); } protected List find(String queryString, int limit) { return find(queryString, null, 0, limit).getData(); } protected List find(String queryString, Object[] values) { return find(queryString, values, -1, -1).getData(); } protected List find(String queryString, Object[] values, Type[] types) { return find(queryString, values, types, -1, -1).getData(); } protected Result find(String queryString, Object parameter, int start, int limit) { return find(queryString, new Object[] { parameter }, start, limit); } protected Result find(String queryString, int start, int limit) { return find(queryString, null, start, limit); } protected Result find(String queryString, Object[] values, int start, int limit) { return find(queryString, values, null, start, limit); } protected Result find(String queryString, Object[] values, Type[] types, int start, int limit) { return find(null, queryString, values, types, start, limit, true); } protected Result find(String countQueryString, String queryString, Object parameter, int start, int limit) { return find(countQueryString, queryString, new Object[] { parameter }, null, start, limit, true); } protected List findForUpdate(String queryString, Object[] values, Type[] types) { return findForUpdate(null, queryString, values, types, -1, -1).getData(); } protected Result findForUpdate(String countQueryString, String queryString, Object[] values, Type[] types, int start, int limit) { return find(countQueryString, queryString, values, types, start, limit, false); } protected Result find(String countQueryString, String queryString, Object[] values, Type[] types, int start, int limit) { return find(countQueryString, queryString, values, types, start, limit, true); } protected Result find(final String countQueryString, final String queryString, final Object[] values, final Type[] types, final int start, final int limit, boolean readOnly) { Result result = new Result(start, limit); if (countQueryString != null && start != -1 && limit != -1) { result.setTotal(count(countQueryString, values, types)); } HibernateTemplate ht = readOnly ? getReadOnlyHibernateTemplate() : getHibernateTemplate(); List data = ht.executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); setParameters(queryObject, values, types); if (start >= 0) { queryObject.setFirstResult(start); } if (limit >= 0) { queryObject.setMaxResults(limit + 1); } return queryObject.list(); } }); result.setData(data); if (start == -1 && limit == -1) { result.setTotal(data.size()); } return result; } protected int count(String queryString) { return count(queryString, null); } protected int count(String queryString, Object[] vlaues) { return count(queryString, vlaues, null); } protected int count(final String queryString, final Object[] values, final Type[] types) { Integer result = (Integer) getReadOnlyHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); setParameters(queryObject, values, types); return queryObject.uniqueResult(); } } ); return result.intValue(); } protected int bulkUpdate(final String queryString, final Object[] values, final Type[] types) throws DataAccessException { Integer updateCount = (Integer) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); setParameters(queryObject, values, types); return new Integer(queryObject.executeUpdate()); } }, true); return updateCount.intValue(); } static void setParameters(Query queryObject, Object[] values, Type[] types) { if (values != null) { if (types != null) { for (int i = 0; i < values.length; i++) { queryObject.setParameter(i, values[i], types[i]); } } else { for (int i = 0; i < values.length; i++) { queryObject.setParameter(i, values[i]); } } } } protected List findBySQL(final String sql, final String entityAlias, final Class entityClass, final Object[] values, final Type[] types) { return findBySQL(null, sql, entityAlias, entityClass, values, types, -1, -1).getData(); } protected Result findBySQL(final String countSql, final String sql, final String entityAlias, final Class entityClass, final Object[] values, final Type[] types, final int start, final int limit) { return findBySQL(countSql, sql, entityAlias, entityClass, values, types, start, limit, true); } protected Result findBySQL(final String countSql, final String sql, final String entityAlias, final Class entityClass, final Object[] values, final Type[] types, final int start, final int limit, boolean readOnly) { HibernateTemplate ht = readOnly ? getReadOnlyHibernateTemplate() : getHibernateTemplate(); Result result = new Result(start, limit); if (countSql != null && start != -1 && limit != -1) { Number count = (Number) ht.execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { return session.createSQLQuery(countSql) .setParameters(values, types) .uniqueResult(); } }); result.setTotal(count.intValue()); } List data = ht.executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { SQLQuery query = session.createSQLQuery(sql); query.addEntity(entityAlias, entityClass); query.setParameters(values, types); if (start >= 0) { query.setFirstResult(start); } if (limit >= 0) { query.setMaxResults(limit + 1); } return query.list(); } }); result.setData(data); if (start == -1 && limit == -1) { result.setTotal(data.size()); } return result; }}
[Java]代码
import org.hibernate.SessionFactory;import org.springframework.orm.hibernate3.HibernateAccessor;import org.springframework.orm.hibernate3.HibernateTemplate;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;/** * <p> * <a href="ExtendedHibernateDaoSupport.java.html"><i>View Source</i></a> * </p> * * @author Zhang Songfu * @version $Id: ExtendedHibernateDaoSupport.java 10855 2009-12-28 10:31:55Z zhangsongfu $ */public class ExtendedHibernateDaoSupport extends HibernateDaoSupport { private HibernateTemplate readOnlyHibernateTemplate = null; public void setReadOnlySessionFactory(SessionFactory sessionFactory) { this.readOnlyHibernateTemplate = new HibernateTemplate(sessionFactory); this.readOnlyHibernateTemplate.setFlushMode(HibernateAccessor.FLUSH_NEVER); } public HibernateTemplate getReadOnlyHibernateTemplate() { return (readOnlyHibernateTemplate == null) ? getHibernateTemplate() : readOnlyHibernateTemplate; }}
[Java]代码
import java.io.Serializable;import java.util.Iterator;import java.util.List;/** * <p> * <a href="ApiObject.java.html"><i>View Source</i></a> * </p> * * @author Zhang Songfu * @version $Id: Result.java 7 2010-05-11 16:23:49Z zhangsf $ */public class Result<T> implements Iterable<T>, Serializable { //~ Static fields/initializers ============================================= private static final long serialVersionUID = -3227685040036327514L; //~ Instance fields ======================================================== private int offset; private int size; private int total; private List<T> data; private List<T> requestedData; //~ Constructors =========================================================== public Result() { } public Result(int offset, int size) { this(null, offset, size); } public Result(List<T> data, int offset, int size) { this.data = data; this.offset = offset; this.size = size; } //~ Methods ================================================================ public boolean isFirst() { return offset == 0; } public boolean isLast() { return !hasNext(); } public boolean hasNext() { if (data == null || size < 0) { return false; } return data.size() > size; } public int getTotalPage() { if (size < 0) return 1; return total % size == 0 ? total/size : total/size + 1; } public int getPage() { return offset/size + 1; } //~ Accessors ============================================================== public void setData(List<T> data) { this.data = data; this.requestedData = null; } public List<T> getData() { if (requestedData == null) { if (size < 0 || data.size() <= size) { requestedData = data; } else { requestedData = data.subList(0, size); } } return requestedData; } public List<T> getOriginalData() { return data; } /** * @see java.lang.Iterable#iterator() */ public Iterator<T> iterator() { return getData().iterator(); } /** * @return Returns the offset. */ public int getOffset() { return offset; } /** * @param offset The offset to set. */ public void setOffset(int offset) { this.offset = offset; } /** * @return Returns the size. */ public int getSize() { return size; } /** * @param size The size to set. */ public void setSize(int size) { this.size = size; } /** * @return Returns the total. */ public int getTotal() { return total; } /** * @param total The total to set. */ public void setTotal(int total) { this.total = total; }}
[Java]代码
import java.io.Serializable;import java.util.List;/** * Data Access Object (DAO) interface. This is an interface * used to tag our DAO classes and to provide common methods to all DAOs. * * <p><a href="DAO.java.html"><i>View Source</i></a></p> * * @author <a href="mailto:songfu.zhang@gmail.com">zhang songfu</a> */public interface DAO { /** * Generic method used to get all objects of a particular type. This * is the same as lookup up all rows in a table. * @param clazz the type of objects (a.k.a. while table) to get data from * @return List of populated objects */ public List getObjects(Class clazz); /** * 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 */ public Object getObject(Class clazz, Serializable id); /** * Generic method to save an object - handles both update and insert. * @param o the object to save */ public void saveObject(Object o); /** * Generic method to delete an object based on class and id * @param clazz model class to lookup * @param id the identifier (primary key) of the class */ public void removeObject(Class clazz, Serializable id); /** * Generic method to delete an object * @param o the object to be deleted */ public void removeObject(Object o);}
用户点评