hibernate配置多個數據源及事物(以兩個數據源爲例)

原文鏈接

在ssh項目中,需要連接兩個不同ip下的數據庫,所以必須要給hibernate配置兩個或多個數據源

因爲我只有一臺電腦,所以我配置的是sqlserver+MySQL兩個數據源

首先hibernate配置是直接從myeclipse中添加的   右鍵----myeclipse-----add hibernate

之後會生成 hibernate.cfg.xml文件,這個文件是配置數據源的,因爲咱們需要鏈接兩個數據源,所以將文件拷貝一份重命名mysql.cfg.xml

以下是部分代碼

sqlserver數據源配置

<property name="connection.url">
   jdbc:sqlserver://localhost:1433;databaseName=chdb
  </property>
  <property name="connection.username">sa</property>
  <property name="connection.password">123</property>

  <property name="dialect">
   org.hibernate.dialect.SQLServerDialect
  </property>
  <property name="myeclipse.connection.profile">testpro</property>
  <property name="connection.driver_class">
   com.microsoft.sqlserver.jdbc.SQLServerDriver
  </property>

mysql數據源配置

<property name="connection.url">jdbc:mysql://localhost:3306/lenovo</property>
  <property name="connection.username">root</property>
  <property name="connection.password">123</property>

  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="myeclipse.connection.profile">mysql</property>
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

修改HibernateSessionFactory

代碼如下:

package com.changh.common;

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 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 String MYSQL_CONFIG_FILE_LOCATION = "/mysql.cfg.xml";
 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
 private static final ThreadLocal<Session> mythreadLocal = new ThreadLocal<Session>();//因爲每一個threadLocal有一個id,所以如果同時使用兩個數據源的話必須是兩個threadlocal
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private  static Configuration Myconfiguration = new Configuration();    
    private static org.hibernate.SessionFactory MysessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;
    private static String mysqlconfigFile = MYSQL_CONFIG_FILE_LOCATION;

 static {
     try {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
   Myconfiguration.configure(mysqlconfigFile);
   MysessionFactory=Myconfiguration.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;
    }
    public static Session getMySession() throws HibernateException {
        Session session = (Session) mythreadLocal.get();

  if (session == null || !session.isOpen()) {
   if (MysessionFactory == null) {
    rebuildSessionFactory();
   }
   session = (MysessionFactory != null) ? MysessionFactory.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;
 }

}

basehibernatedao文件代碼如下:

import com.common.HibernateSessionFactory;

import org.hibernate.Session;


/**
 * Data access object (DAO) for domain model
 * @author MyEclipse Persistence Tools
 */
public class BaseHibernateDAO implements IBaseHibernateDAO {
 
 public Session getSession() {
  return HibernateSessionFactory.getSession();
 }
 public Session getMySession(){
  return HibernateSessionFactory.getMySession();
 }


自定義的事物編寫代碼如下:

public void mergeUser(UserInfo userInfo) {
  Session session = getSession();
  Session mySession=getMySession();
  Transaction tx = session.beginTransaction();
  Transaction tx2 = mySession.beginTransaction();
  com.changh.mysql.vo.Userinfo myuser = new com.changh.mysql.vo.Userinfo();
  try {
   String queryString;
   myuser.setUsername(userInfo.getUserName());
   myuser.setPassword(userInfo.getPassword());
   mySession.merge(myuser);
   if (userInfo.getId()==null) {
    session.save(userInfo);
   }else {
    session.update(userInfo);
   }
    UserInfoRole userInfoRole = new UserInfoRole();
    userInfoRole.setRoleId(Integer.parseInt(userInfo.getRoleId()));
    userInfoRole.setUserInfoId(userInfo.getId());
    session.merge(userInfoRole);
   }else {
    
   }
   tx2.commit();
   tx.commit();
  } catch (RuntimeException re) {
   tx2.rollback();
   tx.rollback();
   log.error(re);// 記錄錯誤日誌
   throw re;
  } finally {
   session.close();
  }
 }
 

參考文件:http://zhidao.baidu.com/link?url=g2cNFtpE9r5tsCBkYf2ES0NYXZndVk-vw8DoiXgFI2HfFRKduRy4UyDZIs3f3IZTei8-E22gYsud0VavmTvAAK


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章