Hibernate方言dialectによるマルチデータベースの動的接続
Hibernateは方言dialectに基づいてマルチデータベースを動的に接続する.最近はウェブプロジェクトで異なるアドレスのデータベースを動的にリンクする必要があり,リンクするサブデータベースの情報が総データベース(すなわちウェブプロジェクトのメインデータベース)のテーブルにあるため,クラスを手書きした.Webプロジェクトではhibernateを試用し、動的に生成されたサブデータベースリンクもhibernateを使用しようとしたが、動的に生成されたsessionfactoryクラス、およびコンフィギュレーション構成ではサブデータベースのオブジェクト関係マッピングがないが、native SQLを使用するのも便利である.
後から書いた改善編を見て、何かアドバイスがあればメッセージをお願いします---------
Hibernateダイナミック接続マルチデータベース改善編
-------------------------------------------------------
コードは次のとおりです.
public class TempSessionFactory {
/**
* 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 final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private Configuration configuration = new Configuration();
private 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();
}
}*/
public void setConfiguration(String dialect, String driverClass,
String ipAddress, String port, String dataBaseName,
String username, String password) {
String connection_url = "";
Configuration configuration = new Configuration();
if (dialect.indexOf("MySQL") > -1) {
System.out.println("%%%% DataBase type is MySql %%%%");
connection_url = "jdbc:mysql://" + ipAddress + "/" + dataBaseName;
} else if (dialect.indexOf("SQLServer") > -1) {
System.out.println("%%%% DataBase type is SQLServer %%%%");
connection_url = "jdbc:sqlserver://" + ipAddress + ":" + port
+ ";DataBaseName=" + dataBaseName;
} else if (dialect.indexOf("Oracle") > -1) {
System.out.println("%%%% DataBase type is Oracle %%%%");
connection_url = "jdbc:oracle:thin:@" + ipAddress + ":" + port
+ ":" + dataBaseName;
// configuration.setProperty("hibernate.connection.oracle.jdbc.V8Compatible","true");
}
configuration.setProperty("hibernate.dialect", dialect);
configuration.setProperty("hibernate.connection.url", connection_url);
configuration.setProperty("hibernate.connection.driver_class",
driverClass);
configuration.setProperty("hibernate.connection.username", username);
configuration.setProperty("hibernate.connection.password", password);
// configuration.setProperty("hibernate.default_schema", "dbo");
// configuration.setProperty("hibernate.default_catalog", dataBaseName);
// configuration.setProperty("hibernate.show_sql", "true");
this.configuration = configuration;
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*
*/
public 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 void rebuildSessionFactory() {
try {
//configuration.configure(configFile);
sessionFactory = this.configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public 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 Configuration getConfiguration() {
return configuration;
}
}
テストクラスコード:databasename 1ライブラリにtesttableテーブル、フィールドid、name 2個databasename 2ライブラリにtesttable 2テーブル、フィールドid、name 2個を作成
public class TestCase1 {
public static void main(String[] args) {
try{
Configuration configuration1 = new Configuration();
TempSessionFactory tempSessionFactory1 = new TempSessionFactory(configuration1);
tempSessionFactory1.setConfiguration("org.hibernate.dialect.SQLServerDialect","com.microsoft.sqlserver.jdbc.SQLServerDriver",
"jdbc:sqlserver://*1.*1.*1.*1","1433","databasename1","sa","sa");
Session session1=tempSessionFactory1.getSession();
Transaction tx1 = session1.beginTransaction();
Query query1 = session1.createSQLQuery("select name as aaa from testtable ").setResultTransformer(
Transformers.ALIAS_TO_ENTITY_MAP);
Map obj1 = (Map)query1.setMaxResults(1).uniqueResult();
System.out.println("fd1111===="+obj1.get("aaa"));
Configuration configuration2 = new Configuration();
TempSessionFactory tempSessionFactory2 = new TempSessionFactory(configuration2);
tempSessionFactory2.setConfiguration("org.hibernate.dialect.SQLServerDialect","com.microsoft.sqlserver.jdbc.SQLServerDriver",
"jdbc:sqlserver://*2.*2.*2.*2","1433","databasename2","sa","sa");
Session session2=tempSessionFactory2.getSession();
Transaction tx2 = session2.beginTransaction();
Query query2 = session2.createSQLQuery("select name as aaa from testtable2 ").setResultTransformer(
Transformers.ALIAS_TO_ENTITY_MAP);
Map obj2 = (Map)query2.setMaxResults(1).uniqueResult();
System.out.println("fd2222===="+obj2.get("aaa"));
}catch (Exception e) {
System.err.println(e);
// TODO: handle exception
}
}
}
後に書いた改善編を見てください----------------------
Hibernateダイナミック接続マルチデータベース改善編
------------------------------------------