Technorati 标签:

一、常见 hibernate 配置 xml (hibernate.cfg.xml)

   1: <?xml version="1.0" encoding="UTF-8"?>
   2: <!DOCTYPE hibernate-configuration PUBLIC
   3:         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
   4:         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
   5:         
   6: <hibernate-configuration>
   7:     <session-factory name="SessionFactory">
   8:         <!-- 数据库驱动 -->
   9:         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  10:         <!-- 数据库连接用户名 -->
  11:         <property name="hibernate.connection.username">user</property> 
  12:         <!-- 数据库连接密码 -->
  13:         <property name="hibernate.connection.password">root</property>
  14:         <!-- 数据库连接URL-->
  15:         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db_database20</property>
  16:           <!-- 数据库方言 -->
  17:         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  18:         <!-- 是否在控制台输出SQL语句 -->
  19:         <property name="hibernate.show_sql">null</property>
  20:         <!-- 是否启动查询缓存 -->
  21:         <property name="hibernate.cache.use_query_cache">false</property>
  22:         <!-- 批量加载控制策略,该值一般控制到小于10的范围 -->
  23:         <property name="hibernate.jdbc.batch_size">10</property>
  24:         <!-- 限定out-join检索层次,用于预读加载机制 -->
  25:         <property name="hibernate.max_fetch_depth">5</property>
  26:            <!-- C3P0连接池 -->
  27:            <property name="hibernate.connection.provider_class">
  28:                org.hibernate.connection.C3P0ConnectionProvider
  29:            </property>
  30:            <!-- 连接池中可用的数据库连接的最少数目 -->
  31:            <property name="hibernate.c3p0.min_size">5</property>
  32:            <!-- 连接池中可用的数据库连接的最大数目 -->    
  33:            <property name="hibernate.c3p0.max_size">20</property>    
  34:            <!-- 数据库连接的过期时间,以秒为单位 -->
  35:            <property name="hibernate.c3p0.timeout">300</property>    
  36:            <!-- 可以被缓存的PreparedStatement实例的最大数目 -->
  37:            <property name="hibernate.c3p0.max_statements">50</property>
  38:            <!-- 在使数据库连接自动生效之前处于空闲状态的时间,以秒为单位 -->
  39:            <property name="hibernate.c3p0.idle_test_period">3000</property >
  40:            
  41:           <!-- proxool连接池
  42:          <property name="hibernate.connection.provider_class">
  43:              org.hibernate.connection.ProxoolConnectionProvider
  44:          </property>
  45:      
  46:            <property name="hibernate.proxool.pool_alias">pool1</property>
  47:        
  48:            <property name="hibernate.proxool.xml">ProxoolConf.xml</property >
  49:           -->
  50:           <!-- 加载映射文件 -->
  51:            <mapping resource=".....hbm.xml"/>   
  52:            <mapping resource=".....hbm.xml"/>                                          
  53:     </session-factory>
  54: </hibernate-configuration>

二、获取数据源的的公共类 getSession()

   1: public class SessionFactoryProvider {
   2:  
   3:     // Hibernate配置文件的路径的变量
   4:     private static String CONFIG_FILE = "/hibernate.cfg.xml";
   5:     // 创建一个线程本地变量
   6:     private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
   7:     // 配置 Hibernate的类 ,根启动Hibernate,创建SessionFactory实例
   8:     private static Configuration configuration = new Configuration();
   9:     // 声明私有类型的SessionFactory
  10:     private static SessionFactory sessionFactory;
  11:     static {
  12:         try {
  13:             configuration.configure(CONFIG_FILE); // 加载Hibernate配置文件
  14:             sessionFactory = configuration.buildSessionFactory(); // 根据配置文件创建SessionFactory实例
  15:         } catch (Exception e) {
  16:             e.printStackTrace();
  17:         }
  18:     }
  19:  
  20:     private SessionFactoryProvider() {
  21:     }
  22:  
  23:     /**
  24:      * 静态方法,用于获取Session实例
  25:      * 
  26:      * @return
  27:      * @throws HibernateException
  28:      */
  29:     public static Session getSession() throws HibernateException {
  30:         Session session = (Session) threadLocal.get(); // 获取此线程局部变量的当前线程副本中的session
  31:         if (session == null || !session.isOpen()) { // 判断Session实例是否存在
  32:             if (sessionFactory == null) {// 判断SessionFactory实例是否为空,如果为空重建SessionFactory实例
  33:                 rebuildSessionFactory();
  34:             }
  35:             session = (sessionFactory != null) ? sessionFactory.openSession() : null;// 从SessionFactory实例中获取Session实例
  36:             threadLocal.set(session);// 将此线程局部变量的当前线程副本中的值设置为session
  37:         }
  38:         return session;
  39:     }
  40:  
  41:     /**
  42:      * 静态方法,重建SessionFactory实例
  43:      */
  44:     public static void rebuildSessionFactory() {
  45:         try {
  46:             configuration.configure(CONFIG_FILE);
  47:             sessionFactory = configuration.buildSessionFactory();
  48:         } catch (Exception e) {
  49:             e.printStackTrace();
  50:         }
  51:     }
  52:  
  53:     /**
  54:      * 静态方法,关闭Session
  55:      * 
  56:      * @throws HibernateException
  57:      */
  58:     public static void closeSession() throws HibernateException {
  59:         Session session = (Session) threadLocal.get();
  60:         threadLocal.set(null);
  61:         if (session != null) {
  62:             session.close();
  63:         }
  64:     }
  65:  
  66:     /**
  67:      * 获取SessionFactory实例
  68:      * 
  69:      * @return
  70:      */
  71:     public static SessionFactory getSessionFactory() {
  72:         return sessionFactory;
  73:     }
  74:  
  75:     /**
  76:      * 设置Hibernate的配置文件路径名
  77:      * 
  78:      * @param configFile
  79:      */
  80:     public static void setConfigFile(String configFile) {
  81:         SessionFactoryProvider.CONFIG_FILE = configFile;
  82:         sessionFactory = null;
  83:     }
  84:  
  85:     /**
  86:      * 获取用于配置Hibernate的配置对象
  87:      * 
  88:      * @return
  89:      */
  90:     public static Configuration getConfiguration() {
  91:         return configuration;
  92:     }
  93: }

三、数据库常用操作(与 spring 结合)

   1:  
   2: import java.io.Serializable;
   3: import java.util.List;
   4: //数据库的常用操作
   5: public interface GenericDao<T, PK extends Serializable> {
   6:     //通过 id 寻找 entity
   7:     public T findById(PK id);
   8:     //查询所有 entity
   9:     public List<T> findAll();
  10:     //保存某个 entity
  11:     public T save(T entity);
  12:     //更新
  13:     public void update(T entity);
  14:     //删除
  15:     public void delete(T entity);
  16: }

   1: import java.io.Serializable;
   2: import java.lang.reflect.ParameterizedType;
   3: import java.sql.SQLException;
   4: import java.util.List;
   5: import org.hibernate.*;
   6: import org.springframework.orm.hibernate3.HibernateCallback;
   7: import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
   8:  
   9: public abstract class GenericDaoHibernate<T, PK extends Serializable> extends HibernateDaoSupport
  10:         implements GenericDao<T, PK> {
  11:     private Class<T> clazz;
  12:  
  13:     public GenericDaoHibernate() {
  14:         clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
  15:                 .getActualTypeArguments()[0];
  16:     }
  17:  
  18:     public T findById(PK id) {
  19:         return (T) getHibernateTemplate().get(clazz, id);
  20:     }
  21:  
  22:     public List<T> findAll() {
  23:         return getHibernateTemplate().find("from " + clazz.getName());
  24:     }
  25:  
  26:     public T save(T entity) {
  27:         getHibernateTemplate().save(entity);
  28:         return entity;
  29:     }
  30:  
  31:     public void update(T entity) {
  32:         getHibernateTemplate().update(entity);
  33:     }
  34:  
  35:     public void delete(T entity) {
  36:         getHibernateTemplate().delete(entity);
  37:     }
  38:  
  39:     public Object queryObject(final String hql, final Object[] params) {
  40:         return getHibernateTemplate().execute(new HibernateCallback() {
  41:             public Object doInHibernate(Session session) throws HibernateException, SQLException {
  42:                 Query query = session.createQuery(hql);
  43:                 if (params != null) {
  44:                     for (int i = 0; i < params.length; i++) {
  45:                         query.setParameter(i, params);
  46:                     }
  47:                 }
  48:                 return query.uniqueResult();
  49:             }
  50:         });
  51:     }
  52:     //分页功能的实现
  53:     public Pagination getPagination(final String hql, final Object params[], final int pageSize,
  54:             final int pageNumber, final int totalCount) {
  55:         return ((Pagination) getHibernateTemplate().execute(new HibernateCallback() {
  56:             public Object doInHibernate(Session session) throws HibernateException, SQLException {
  57:                 Pagination pagination = new Pagination(pageSize, pageNumber, totalCount);
  58:                 Query query = session.createQuery(hql);
  59:                 if (params != null) {
  60:                     for (int i = 0; i < params.length; i++) {
  61:                         query.setParameter(i, params);
  62:                     }
  63:                 }
  64:                 query.setFirstResult((pageNumber - 1) * pageSize);
  65:                 query.setMaxResults(pageSize);
  66:                 pagination.setList(query.list());
  67:                 return pagination;
  68:             }
  69:         }));
  70:     }
  71: }

附 Pagination 类的代码如下:

   1: import java.util.List;
   2:  
   3: public class Pagination {
   4:     private int pageSize = 20;
   5:     private int pageNumber = 1;
   6:     private int maxElements;
   7:     private List list;
   8:     private int offset;
   9:  
  10:     public Pagination() {
  11:  
  12:     }
  13:  
  14:     public Pagination(int maxElements) {
  15:         this.maxElements = maxElements;
  16:     }
  17:  
  18:     public Pagination(int pageSize, int pageNumber, int maxElements) {
  19:         this.pageSize = pageSize;
  20:         this.maxElements = maxElements;
  21:         this.pageNumber = pageNumber;
  22:     }
  23:  
  24:     public int getPageNumber() {
  25:         return pageNumber;
  26:     }
  27:  
  28:     public void setPageNumber(int pageNumber) {
  29:         int total = (int) Math.ceil(maxElements / pageSize);
  30:         if (pageNumber > total) {
  31:             this.pageNumber = total;
  32:         } else if (pageNumber <= 1) {
  33:             pageNumber = 1;
  34:         }else{
  35:             this.pageNumber = pageNumber;
  36:         }
  37:     }
  38:  
  39:     public void setMaxElments(int maxElements) {
  40:         this.maxElements = maxElements;
  41:     }
  42:  
  43:     public int getMaxElements() {
  44:         return maxElements;
  45:     }
  46:  
  47:     public int getOffset() {
  48:         return offset;
  49:     }
  50:  
  51:     public void setOffset(int offset) {
  52:         if (offset <= 0) {
  53:             this.offset = 0;
  54:         } else if (offset > maxElements) {
  55:             this.offset = maxElements-1;
  56:         } else {
  57:             this.offset = offset;
  58:         }
  59:     }
  60:  
  61:     public int getPageSize() {
  62:         return pageSize;
  63:     }
  64:  
  65:     public void setList(List list) {
  66:         this.list = list;
  67:     }
  68:  
  69:     public List getList() {
  70:         return list;
  71:     }
  72: }