package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.sun.crypto.provider.RC2Cipher; /** * * @author Administrator * Data access layer class group * */ public class BaseDao { /* * Open Database Connectivity */ public Connection getConn(){ Connection conn = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace (); } return conn; } /* * Close method * Release resources * After opening the first off */ public void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace (); } } if(pstmt!=null){ try { pstmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace (); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace (); } } } /* * Universal method * Can only add, delete, change. * You can not check */ public int executeSql(String sql,Object[] param){ Connection conn = null; // database connection PreparedStatement pstmt = null; int num = 0; try { conn = this.getConn (); // get the database connection pstmt = conn.prepareStatement(sql); if(param!=null){ for (int i = 0; i < param.length; i++) { pstmt.setObject(i+1, param[i]); } } num = pstmt.executeUpdate (); // add, delete, change all with this method } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace (); }finally{ this.closeAll(conn, pstmt,null); } Surely return; } }
BaseHibernateDAO
package dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Example; /** * * To operate the database underlying class * */ public abstract class BaseHibernateDAO { private Session session; private boolean isClose = false; // if the caller is closed Session /** * * @Param cla * @param id * @return */ protected Object getObject(Class cla,java.io.Serializable id){ Object object = null; session = this.getSession(); try{ object = session.get(cla, id); }catch(Exception ex){ ex.printStackTrace(); }finally{ if(!isClose){ this.closeSession(); } } return object; } /** * * @Param cla * @param id * @return */ protected Object loadObject(Class cla,java.io.Serializable id){ Object object = null; session = this.getSession(); try{ object = session.load(cla, id); }catch(Exception ex){ ex.printStackTrace(); }finally{ if(!isClose){ this.closeSession(); } } return object; } /** * adding data */ protected boolean add(Object object){ Transaction tx = null; session = this.getSession(); try{ tx = session.beginTransaction (); // open affairs session.save(object); tx.commit (); // commit the transaction }catch(Exception ex){ if(tx!=null)tx.rollback();//回滚 ex.printStackTrace(); return false; }finally{ if(!isClose) this.closeSession(); } return true; } /** * change the data */ protected boolean update(Object object){ Transaction tx = null; session = this.getSession(); try{ tx = session.beginTransaction (); // open affairs session.update(object); tx.commit (); // commit the transaction }catch(Exception ex){ if(tx!=null)tx.rollback();//回滚 ex.printStackTrace(); return false; }finally{ if(!isClose) this.closeSession(); } return true; } /** * delete data */ protected boolean delete(Class cls,java.io.Serializable id){ Transaction tx = null; Object object = this.getObject(cls, id); session = this.getSession(); try{ tx = session.beginTransaction (); // open affairs session.delete (object); // get the object and for deletion tx.commit (); // commit the transaction }catch(Exception ex){ if(tx!=null)tx.rollback();//回滚 ex.printStackTrace(); return false; }finally{ if(!isClose) this.closeSession(); } return true; } /** * delete data */ protected boolean deleteAll(String sql){ Transaction tx = null; session = this.getSession(); try{ tx = session.beginTransaction (); // open affairs Query query = session.createQuery(sql.toString()); int i = query.executeUpdate(); System.out.println("======="+i); // get the object and for deletion tx.commit (); // commit the transaction }catch(Exception ex){ if(tx!=null)tx.rollback();//回滚 ex.printStackTrace(); return false; }finally{ if(!isClose) this.closeSession(); } return true; } /** * Advanced accordance with the conditions */ protected List search(Class clazz,Object condition){ List list = null; try { List results = this.getSession().createCriteria(clazz).add(Example.create(condition)).list(); return results; } catch (Exception e) { return list; }finally{ if(!isClose) this.closeSession(); } } /** * Based on SQL queries */ protected List selectBySql(String sql){ List list = null; try{ list = this.getSession().createSQLQuery(sql).list(); return list; }catch(Exception ex){ ex.printStackTrace(); return list; }finally{ if(!isClose) this.closeSession(); } } /** * According to HQL query */ protected List selectByHql(String Hql){ List list = null; session = this.getSession(); try{ list = session.createQuery(Hql).list(); return list; }catch(Exception ex){ ex.printStackTrace(); return list; }finally{ if(!isClose) this.closeSession(); } } /** * * @return */ protected Session getSession() { if(this.session==null){ this.session = HibernateSessionFactory.getSession(); System.out.println ( "----- open Session -----"); } return this.session; } public void setSession(Session session) { this.session = session; } public void closeSession(){ this.session = null; HibernateSessionFactory.closeSession(); System.out.println("-----关闭Session-----"); } public void setClose(boolean isClose) { this.isClose = isClose; } }
CommonDao
package com.hljzr.framework.dao; import java.io.Serializable; import java.util.Collection; import java.util.List; public interface CommonDao { /** * Query list (no pagination) * * @Param hql statement * @return list */ public List query(String hql); /** * Query a * * @Param cla Class class * @Param id primary key * @return */ public Object queryById(Class cla, Serializable id); /** * Save a data * * @Param obj Object * @return */ public void save(Object obj); /** * Save a data * * @Param obj Object * @return */ public void save(Collection c); /** * Modify a Data * * @Param obj Object * @return */ public void update(Object obj); /** * Remove a data * * @Param obj Object * @return */ public void delete(Object obj); /** * Delete multiple data * * @Param obj Object * @return */ public void delete(Collection c); /** * Empty session of a particular entity */ public void clear(Object obj); /*** * Paging query * * @param offset * current page number * @param pageSize * The number of display per page * @Return Returns a collection to be queried */ public List findByPage(final String hql, final int offset, final int pageSize); /** * Get the total number of */ Public Long given otal count (String HQL); /** * Get the number of pages to be divided * * @Param pageSize number of displayed per page */ public Long getTotalPages(String hql, Integer pageSize); /** * Single parameter paging query * * @Param hql * @param value * @param offset * @param pageSize * @return */ public List findByPage(final String hql, final Object value, final int offset, final int pageSize); /** * Multiple parameters paging query * * @Param hql * @param values * @param offset * @param pageSize * @return */ public List findByPage(final String hql, final Object[] values, final int offset, final int pageSize); }
CommonDaoImpl
package com.hljzr.framework.dao.impl; import java.io.Serializable; import java.sql.SQLException; import java.util.Collection; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.hljzr.framework.dao.CommonDao; public class CommonDaoImpl extends HibernateDaoSupport implements CommonDao { public List query(String hql) { return super.getHibernateTemplate().find(hql); } public Object queryById(Class cla, Serializable id) { return this.getHibernateTemplate().get(cla, id); } public void save(Object obj) { super.getHibernateTemplate().save(obj); } public void update(Object obj) { super.getHibernateTemplate().update(obj); } public void delete(Object obj) { super.getHibernateTemplate().delete(obj); } public void delete(Collection c) { super.getHibernateTemplate().deleteAll(c); } public void save(Collection c) { super.getHibernateTemplate().saveOrUpdateAll(c); } public void clear(Object obj) { super.getHibernateTemplate().evict(obj); } /*** * Paging query * * @param pageNo * current page number * @param pageSize * The number of display per page * @Return Returns a collection to be queried */ public List findByPage(final String hql, final int pageNo, final int pageSize) { List list = getHibernateTemplate (). ExecuteFind (new HibernateCallback () // callback function { // implementation HibernateCallback interface must be implemented public Object doInHibernate(Session session) throws HibernateException, SQLException { // Hibernate paging query execution List result = session.createQuery(hql).setFirstResult( (PageNo - 1) * pageSize) // index value from "0" .setMaxResults (pageSize) // To display a few .list(); return result; } }); return list; } /** * Get the total number of */ Public Long given otal count (String HQL) { return (Long) super.getHibernateTemplate().find(hql).get(0); } /** * Get the number of pages to be divided */ public Long getTotalPages(String hql, Integer pageSize) { Long totalpages; Long all = this.getTotalCount(hql); totalpages = (all % pageSize == 0) ? (all / pageSize) : (all / pageSize + 1); return totalpages; } /** * Arguments paging query (single parameter) */ public List findByPage(final String hql, final Object value, final int offset, final int pageSize) { // to execute the query by a HibernateCallback objects List list = getHibernateTemplate().executeFind(new HibernateCallback() { // implementation HibernateCallback interface must be implemented public Object doInHibernate(Session session) throws HibernateException, SQLException { // Hibernate paging query execution List result = session.createQuery(hql) // parameters passed to the statement hql .setParameter(0, value).setFirstResult(offset) .setMaxResults(pageSize).list(); return result; } }); return list; } /** * Multiple parameters paging query */ public List findByPage(final String hql, final Object[] values, final int offset, final int pageSize) { // to execute the query by a HibernateCallback objects List list = getHibernateTemplate().executeFind(new HibernateCallback() { // implementation HibernateCallback interface must be implemented public Object doInHibernate(Session session) throws HibernateException, SQLException { // Hibernate paging query execution Query query = session.createQuery(hql); // parameters passed to the statement hql for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } List result = query.setFirstResult(offset).setMaxResults( pageSize).list(); return result; } }); return list; } }