1. 程式人生 > >Hibernate在MyEclipse中的部署,連線MySQL資料庫

Hibernate在MyEclipse中的部署,連線MySQL資料庫

    如今,更多的人使用MyEclipse而不再使用eclipse,MyEclipse比eclipse的方便之處我就不說了,但MyEclipse不是免費的,我也是使用破解版的。
    在MyEclipse中如何搭建hibernate環境呢?今天學習一點點想與大家分享:

1. 在MyEclipse中建立web專案

新建web專案

這裡寫圖片描述

輸入專案名

這裡寫圖片描述

下一步:

這裡寫圖片描述

點選“finish”,建立web專案完成。

2.建立資料庫資源管理器

點選“Open Perspective”

這裡寫圖片描述

找到“MyEclipse Database Explorer”

這裡寫圖片描述

新建資料庫驅動連線

這裡寫圖片描述

Driver template : 根據自己要使用的資料庫選擇;我這裡用的是MySQL資料庫,因此以MySQL為例 。
Driver name : 名字自己隨便寫。
Connection URL : 連線資料庫的URL,不同資料庫連線方式不同。
User name : 資料庫使用者名稱。
Password : 資料庫密碼。
Driver JARs : 新增連線資料庫驅動jar包。
儲存密碼,點選“next”。

這裡寫圖片描述

新增已建立要連線的資料庫

這裡寫圖片描述

在已建專案中安裝hibernate的元件

這裡寫圖片描述

根據自己需要選擇hibernate的版本,我這裡選擇4.1版本

這裡寫圖片描述

建立 Hibernate Configuration 檔案與 SessionFactory 類

這裡寫圖片描述

選擇MySQL,點選“next”

這裡寫圖片描述

點選“finish”完成hibernate環境搭建。

這裡寫圖片描述

3.完成後,將自動生成 hibernate.cfg.xml 檔案與 HibernateSessionFactory.java類

hibernate.cfg.xml 配置檔案

<?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">
<!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">123</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="myeclipse.connection.profile">MySQL</property> </session-factory> </hibernate-configuration>

HibernateSessionFactory.java類

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * 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 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 final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;

    private static Configuration configuration = new Configuration();
    private static ServiceRegistry serviceRegistry; 

    static {
        try {
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } 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();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } 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 hibernate configuration
     *
     */
    public static Configuration getConfiguration() {
        return configuration;
    }

}

注意:自動生成 hibernate.cfg.xml 檔案 HibernateSessionFactory.java類同樣可以自己手動寫。自動生成的 hibernate.cfg.xml 配置檔案不完整,這裡我附上一段我自己寫的 hibernate.cfg.xml 配置檔案

<?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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>

        <!-- 配置連線資料庫的基本資訊 -->
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>

        <!-- 配置hibernate的基本資訊 -->
        <!-- hibernate 所使用的資料庫方言 -->
        <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

        <!-- 執行操作時是否在控制檯列印SQL -->
        <property name="show_sql">true</property>

        <!-- 是否對 SQL 進行格式化  -->
        <property name="format_sql">true</property>

        <!-- 指定自動生成資料表的策略 -->
        <property name="hbm2ddl.auto">update</property>

        <!-- 指定關聯 .hbm.xml -->
        <mapping resource="com/wang/hibernate/model/News.hbm.xml"/>

    </session-factory>

</hibernate-configuration>

完成hibernate環境搭建就可以對hibernate進行開發學習。

學習經驗與大家分享,有不足之處,望能原諒!