您的位置:首页 > 其它

hibernate配置多个数据源及事物(以两个数据源为例)

2014-10-24 20:55 253 查看
在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


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息