[html] <pre name="code" class="html">package www.csdn.project.util; import org.hibernate.Session; /** * Data access interface for domain model * @author MyEclipse Persistence Tools */ public interface IBaseHibernateDAO { public Session getSession(); }</pre><br> <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="myeclipse.connection.profile">localhost</property><property name="connection.url">jdbc:mysql://localhost:3306/bookstore</property><property name="connection.username">root</property><property name="connection.password">root</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="show_sql">true</property><mapping resource="www/csdn/project/domain/Admin.hbm.xml" /></session-factory></hibernate-configuration> <pre></pre> <p><br> </p> <p><br> </p> <p></p> <pre name="code" class="java">package www.csdn.project.dao; import www.csdn.project.domain.Admin; public interface AdminDAO extends BaseDAO<Admin, Integer> { }</pre><br> <pre name="code" class="java">package www.csdn.project.dao; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import www.csdn.project.domain.Admin; import www.csdn.project.util.BaseHibernateDAO; import www.csdn.project.util.HiberSessionFactory; public class AdminDAOImpl extends BaseHibernateDAO implements AdminDAO { public Integer getCountRecord() { int i = 0; try { Query query = this.getSession().createQuery( "select count(admin) from Admin admin"); /* * Long l = (Long) query.uniqueResult(); int i = * Integer.parseInt(l.toString()); */ i = Integer.parseInt(query.uniqueResult().toString()); } catch (Exception e) { e.printStackTrace(); } finally { HiberSessionFactory.closeSession(); } return i; } public List<Admin> getNowPageInfo(Integer nowpage) { List<Admin> entities = new ArrayList<Admin>(); try { entities = this.getSession().createQuery("from Admin") .setFirstResult((nowpage - 1) * PAGESIZE).setMaxResults( PAGESIZE).list(); } catch (Exception e) { e.printStackTrace(); } finally { HiberSessionFactory.closeSession(); } return entities; } /*public Integer getCountRecord(Class className){ int i=0; try { i = this.getSession().createCriteria(className).list().size(); } catch (Exception e) { e.printStackTrace(); } finally { HiberSessionFactory.closeSession(); } return 0; }*/ public Integer getCountRecord(Class<Admin> className) { int i = 0; try { Query query = this.getSession().createQuery( "select count(c) from "+className.getName()+" c"); /* * Long l = (Long) query.uniqueResult(); int i = * Integer.parseInt(l.toString()); */ i = Integer.parseInt(query.uniqueResult().toString()); } catch (Exception e) { e.printStackTrace(); } finally { HiberSessionFactory.closeSession(); } return i; } public List<Admin> getNowPageInfo(Integer nowpage, Class<Admin> className) { List<Admin> entities = new ArrayList<Admin>(); try { entities = this.getSession().createCriteria(className).setFirstResult( (nowpage - 1) * PAGESIZE).setMaxResults(PAGESIZE).list(); } catch (Exception e) { e.printStackTrace(); } finally { HiberSessionFactory.closeSession(); } return entities; } } </pre><br> <pre name="code" class="java">package www.csdn.project.dao; import java.util.List; public interface BaseDAO<T, PK> { // 每頁顯示的記錄數 public static final Integer PAGESIZE = 2; /** * 查詢總記錄數 * * @return */ public Integer getCountRecord(Class<T> className); /** * 查詢當前頁信息 * * @param nowpage * @param entity * @return */ public List<T> getNowPageInfo(Integer nowpage,Class<T> className); } </pre><br> <pre name="code" class="java">package www.csdn.project.dao; import www.csdn.project.domain.Admin; public class Test { public static void main(String[] args) { Admin entity = new Admin(); System.out.println(entity.getClass()); } } </pre><br> <pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="www.csdn.project.domain.Admin" table="admin" catalog="bookstore"> <id name="adminId" type="java.lang.Integer"> <column name="adminId" /> <generator class="identity" /> </id> <property name="adminName" type="java.lang.String"> <column name="adminName" length="20" not-null="true" unique="true" /> </property> <property name="adminPassword" type="java.lang.String"> <column name="adminPassword" length="10" not-null="true" /> </property> <property name="adminEmail" type="java.lang.String"> <column name="adminEmail" length="30" /> </property> </class> </hibernate-mapping> </pre><br> <pre name="code" class="java">package www.csdn.project.domain; /** * Admin entity. @author MyEclipse Persistence Tools */ public class Admin implements java.io.Serializable { // Fields private Integer adminId; private String adminName; private String adminPassword; private String adminEmail; // Constructors /** default constructor */ public Admin() { } /** minimal constructor */ public Admin(String adminName, String adminPassword) { this.adminName = adminName; this.adminPassword = adminPassword; } /** full constructor */ public Admin(String adminName, String adminPassword, String adminEmail) { this.adminName = adminName; this.adminPassword = adminPassword; this.adminEmail = adminEmail; } // Property accessors public Integer getAdminId() { return this.adminId; } public void setAdminId(Integer adminId) { this.adminId = adminId; } public String getAdminName() { return this.adminName; } public void setAdminName(String adminName) { this.adminName = adminName; } public String getAdminPassword() { return this.adminPassword; } public void setAdminPassword(String adminPassword) { this.adminPassword = adminPassword; } public String getAdminEmail() { return this.adminEmail; } public void setAdminEmail(String adminEmail) { this.adminEmail = adminEmail; } @Override public String toString() { return "Admin [adminEmail=" + adminEmail + ", adminId=" + adminId + ", adminName=" + adminName + ", adminPassword=" + adminPassword + "]"; } }</pre><br> <pre name="code" class="java">package www.csdn.project.service; import java.util.List; public interface BaseService<T,PK> { /** * 查詢所有實體對象 * * @param entityClass * @return */ public List<T> getAllObjects(Class<T> entityClass); /** * 根據id查詢實體對象 * @param entityClass * @param id * @return */ public T getObjectById(Class<T> entityClass,PK id); /** * 根據id查詢實體對象 * @param entityClass * @param id * @return */ public T loadObjectById(Class<T> entityClass, PK id); /** * 保存實體對象 * @param entity */ public void saveObject(T entity); /** * 刪除實體操作 * @param entity */ public void deleteObject(T entity); /** * 根據id刪除實體對象 * @param id */ public void deleteObjectById(PK id); /** * 更新實體操作 * * @param entity */ public void updateObject(T entity); } </pre><br> 測試類 <p></p> <p></p> <pre name="code" class="java">package www.csdn.project.test; import java.util.List; import org.junit.Test; import www.csdn.project.dao.AdminDAO; import www.csdn.project.dao.AdminDAOImpl; import www.csdn.project.domain.Admin; import www.csdn.project.util.Pagination; public class AdminTest { @Test public void test(){ //查詢Admin User Good Pagination<Admin> pagination = new Pagination<Admin>(Admin.class,1); System.out.println(pagination.getCountRecond()); System.out.println(pagination.getCountPage()); System.out.println(pagination.getNowPage()); List<Admin> entities = pagination.getEntities(); for(Admin entity:entities){ System.out.println(entity.toString()); } } } </pre><br> <br> <pre name="code" class="java">package www.csdn.project.util; import org.hibernate.Session; /** * Data access object (DAO) for domain model * @author MyEclipse Persistence Tools */ public class BaseHibernateDAO implements IBaseHibernateDAO { public Session getSession() { return HiberSessionFactory.getSession(); } }</pre><pre name="code" class="java">package www.csdn.project.util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HiberSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HiberSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HiberSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }</pre><br> <pre name="code" class="java">package www.csdn.project.util; import java.util.ArrayList; import java.util.List; /** * * @author Zhangguoliang * 寫 牛掰的分頁(通用) * * @param <T> */ public class Pagination<T> extends BaseHibernateDAO { // 每頁顯示的記錄數 private static final Integer PAGESIZE = 2; // 總頁數 private Integer countPage; // 當前頁 private Integer nowPage; // 總記錄數 private Integer countRecond; // 當前頁數據 private List<T> entities; public Pagination(Class<T> className, int nowPage) { this.countRecond = getCountRecord(className); this.nowPage = nowPage; this.countPage = this.countRecond % PAGESIZE == 0 ? this.countRecond / PAGESIZE : this.countRecond /PAGESIZE + 1; this.entities = getNowPageInfo(this.nowPage, className); } public Integer getCountPage() { return countPage; } public void setCountPage(Integer countPage) { this.countPage = countPage; } public Integer getNowPage() { return nowPage; } public void setNowPage(Integer nowPage) { this.nowPage = nowPage; } public Integer getCountRecond() { return countRecond; } public void setCountRecond(Integer countRecond) { this.countRecond = countRecond; } public List<T> getEntities() { return entities; } public void setEntities(List<T> entities) { this.entities = entities; } public Integer getCountRecord(Class<T> className) { int i = 0; try { i = Integer.parseInt(this.getSession().createQuery( "select count(c) from " + className.getName() + " c") .uniqueResult().toString()); } catch (Exception e) { e.printStackTrace(); } finally { HiberSessionFactory.closeSession(); } return i; } @SuppressWarnings("unchecked") public List<T> getNowPageInfo(Integer nowpage, Class<T> className) { List<T> entities = new ArrayList<T>(); try { entities = this.getSession().createCriteria(className) .setFirstResult((nowpage - 1) * PAGESIZE).setMaxResults( PAGESIZE).list(); } catch (Exception e) { e.printStackTrace(); } finally { www.2cto.com HiberSessionFactory.closeSession(); } return entities; } } </pre><br> <br> <br> <p></p>