现在的位置: 首页 > 综合 > 正文

hibernate环境搭建

2013年08月20日 ⁄ 综合 ⁄ 共 4746字 ⁄ 字号 评论关闭
文章目录

(1)添加hibernate开发所必须的jar包:

antlr-2.x.x.jar 语言转换工具,hibernate利用它实现HQL到SQL的转换
dom4j-1.x.x.jar 用于解析xml文件(解析hibernate.cfg.xml文件)
hibernate-core-4.x.x.Final.jar  
hibernate-jpa-2.x-api-x.x.x.jar 对JPA(Java持久化API)规范的支持
javassist-3.x.x.GA.jar 一个开源的分析、编辑和创建Java字节码的类库(struts2也需要用)
hibernate-commons-annotations-4.0.1.Final.jar 用于支持annotation注解(必须)
commons-collection-3.x.jar 对collection集合的封装

(2)创建一个HibernateSessionFactory类,单例化session工厂(非必须,官方推荐使用)

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {

    /** 
     * 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();     //使用xml方式时    
   // private  static AnnotationConfiguration configuration = new AnnotationConfiguration();   //使用annotation注解方式时
    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 HibernateSessionFactory() {
    }
	
   /**
     * 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) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

    /**
     *  return hibernate configuration
     *
     */
      public static Configuration getConfiguration() {
		return configuration;
      }
} 

(3)创建hibernate映射文件

<?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>
         <!-- 设置validation.mode为none,默认是auto -->
        <property name="javax.persistence.validation.mode">none</property>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="connection.url">jdbc:sqlserver://localhost:1433;databaseName=student</property> 
        <property name="connection.username">sa</property> <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) --> 
        <!-- <property name="connection.pool_size">1</property> --> 
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.SQLServer2008Dialect</property> 

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property> 

        <!-- Disable the second-level cache -->
        <!--<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> -->

        <!-- 是否在控制台显示sql语句 --> 
        <property name="show_sql">true</property> 

        <!-- 是否显示更漂亮的sql语句 -->
        <property name="format_sql">true</property> 

        <!-- 服务器启动时数据库表的更新方式 -->
        <property name="hbm2ddl.auto">create</property> 

        <!--create:启动的时候先drop,再create--> 
        <!--create-drop:启动时create,服务器关闭时drop-->
        <!--update:启动的时候检查schema是否一致,如果不一致则做scheme更新-->
        <!--validate:启动时验证现有schema与配置的hibernate是否一致,如果不一致就抛出异常,并不做更新--> 
        <!-- xml方式导入持久化对象 --> 
        <mapping resource="com/ye/student.hbm.xml"/> 

        <!-- annotation方式导入持久化对象 --> 
        <mapping class="com.ye2.student"/> 
        <mapping class="com.ye2.course"/> 
   </session-factory>
</hibernate-configuration>

Note:  (1)  使用annotation时必须将private  static Configuration configuration = new Configuration(); 改为private  static AnnotationConfiguration configuration = new AnnotationConfiguration();

(2) 在进行与数据库的业务交互中必须使用事务控制,如果不加事务控制,那么增、删、改这些操作都不会产生效果,因为默认情况下,它不会进行自动提交。

抱歉!评论已关闭.