Apache Torque连接多个数据库及其使用
- 1.參見官網上Torque的初始化和配置
- 2.torque.properties配置
- 3.log4j.properties配置
- 4.初始化Torque
- 5.使用
1.參見官網上Torque的初始化和配置
Database handles(數據庫句柄)
A database handle is the name attribute that was used in the <database> tag of the schema.xml file. If the name attribute is not used, then the handle would be ‘default’.
In all examples that follow we will use the handle ‘bookstore’. As Torque has the ability to use multiple databases you can tell it which one to use by default thus(由于Torque能夠使用多個數據庫,因此可以告訴它默認使用哪個數據庫):
torque.database.default=bookstore
The handle name ‘default’ is reserved, as Torque uses it as a reference to the default database. So you should not define the handle ‘default’ yourself (but of course you can use it e.g. in generated code).
Multiple databases
The configuration of multiple databases is very similar to the configurations described in the rest of this section, however you will need to define more than one database handle.
多個數據庫的配置與本節其余部分中描述的配置非常相似,但是需要定義多個數據庫句柄。
2.torque.properties配置
配置文件一般放在classes目錄下
# ------------------------------------------------------------------- # $Id: Torque.properties,v 1.11.2.2 2004/08/24 04:14:32 seade Exp $ # # This is the configuration file for Torque. # # Note that strings containing "," (comma) characters must backslash # escape the comma (i.e. '\,') # # -------------------------------------------------------------------torque.applicationRoot = .# ------------------------------------------------------------------- # # L O G G I N G # # ------------------------------------------------------------------- # We use Log4J for all Torque logging and we embed the log4j # properties within our application configuration. # -------------------------------------------------------------------# This first category is required and the category # must be named 'default'. This is used for all logging # where an explicit category is not specified.log4j.category.org.apache.torque = ALL, org.apache.torque log4j.appender.org.apache.torque = org.apache.log4j.FileAppender #log4j.appender.org.apache.torque.file = C:/work/jxc/logs/torque.log log4j.appender.org.apache.torque.layout = org.apache.log4j.PatternLayout log4j.appender.org.apache.torque.layout.conversionPattern = %d [%t] %-5p %c - %m%n log4j.appender.org.apache.torque.append = false# ------------------------------------------------------------------- # # T O R Q U E P R O P E R T I E S # # ------------------------------------------------------------------- # These are your database settings. Look in the # org.apache.torque.pool.* packages for more information. # # The parameters to connect to the default database. You MUST # configure these properly. # -------------------------------------------------------------------torque.database.default=bookstore torque.database.bookstore.adapter=oracle## # Using commons-dbcp #torque.dsfactory.bookstore.factory=org.apache.torque.dsfactory.SharedPoolDataSourceFactory #torque.dsfactory.bookstore.pool.maxIdle=10 #torque.dsfactory.bookstore.pool.maxActive=50 #torque.dsfactory.bookstore.pool.testOnBorrow=true #torque.dsfactory.bookstore.pool.validationQuery=select * from dual #torque.dsfactory.bookstore.connection.driver = oracle.jdbc.driver.OracleDriver #torque.dsfactory.bookstore.connection.url = jdbc:oracle:thin:@192.168.1.100:1521:bookstore #torque.dsfactory.bookstore.connection.user = oracle #torque.dsfactory.bookstore.connection.password = oracle# # Using c3p0 torque.dsfactory.bookstore.factory=org.apache.torque.dsfactory.C3P0DataSourceFactory #<!--當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數。Default: 3 --> torque.dsfactory.bookstore.pool.acquireIncrement=3 #<!--定義在從數據庫獲取新連接失敗后重復嘗試的次數。Default: 30 --> torque.dsfactory.bookstore.pool.acquireRetryAttempts=30 #<!--兩次連接中間隔時間,單位毫秒。Default: 1000 --> #torque.dsfactory.bookstore.pool.acquireRetryDelay=1000 #<!--當連接池用完時客戶端調用getConnection()后等待獲取新連接的時間,超時后將拋出SQLException,如設為0則無限期等待。 #單位毫秒。Default: 0 --> torque.dsfactory.bookstore.pool.checkoutTimeout=30000 #<!--初始化時獲取三個連接,取值應在minPoolSize與maxPoolSize之間。Default: 3 --> torque.dsfactory.bookstore.pool.initialPoolSize=5 #<!--最大空閑時間,60秒內未使用則連接被丟棄。若為0則永不丟棄。 #單位:秒 Default: 0 --> torque.dsfactory.bookstore.pool.maxIdleTime=0 #<!--連接池中保留的最大連接數。Default: 15 --> torque.dsfactory.bookstore.pool.maxPoolSize=50 #<!--JDBC的標準參數,用以控制數據源內加載的PreparedStatements數量。但由于預緩存的statements #屬于單個connection而不是整個連接池。所以設置這個參數需要考慮到多方面的因素。 #如果maxStatements與maxStatementsPerConnection均為0,則緩存被關閉。Default: 0--> torque.dsfactory.bookstore.pool.maxStatements=150 <!--maxStatementsPerConnection定義了連接池內單個連接所擁有的最大緩存statements數。Default: 0 --> torque.dsfactory.bookstore.pool.maxStatementsPerConnection=0 #<!--c3p0是異步操作的,緩慢的JDBC操作通過幫助進程完成。擴展這些操作可以有效的提升性能 #通過多線程實現多個操作同時被執行。Default: 3--> torque.dsfactory.bookstore.pool.numHelperThreads=3 #<!--每60秒檢查所有連接池中的空閑連接。單位:秒 Default: 0 --> torque.dsfactory.bookstore.pool.idleConnectionTestPeriod=600 #<!--定義所有連接測試都執行的測試語句。在使用連接測試的情況下這個一顯著提高測試速度。注意: #測試的表必須在初始數據源的時候就存在。Default: null--> torque.dsfactory.bookstore.pool.preferredTestQuery=select * from dual #db connnection torque.dsfactory.bookstore.connection.driverClass = oracle.jdbc.driver.OracleDriver torque.dsfactory.bookstore.connection.jdbcUrl = jdbc:oracle:thin:@192.168.1.100:1521:bookstore torque.dsfactory.bookstore.connection.user = oracle torque.dsfactory.bookstore.connection.password = oracle# Determines if the quantity column of the IDBroker's id_table should # be increased automatically if requests for ids reaches a high # volume.torque.idbroker.clever.quantity=false# Determines whether the managers cache instances of the business objects. # And also whether the MethodResultCache will really cache results.torque.manager.useCache = true## 第二個數據庫連接 torque.database=order torque.database.order.adapter=oracletorque.dsfactory.order.factory=org.apache.torque.dsfactory.C3P0DataSourceFactory torque.dsfactory.order.pool.acquireIncrement=2 torque.dsfactory.order.pool.acquireRetryAttempts=30 torque.dsfactory.order.pool.checkoutTimeout=30000 torque.dsfactory.order.pool.initialPoolSize=1 torque.dsfactory.order.pool.maxIdleTime=0 torque.dsfactory.order.pool.maxPoolSize=50 torque.dsfactory.order.pool.maxStatements=150 torque.dsfactory.order.pool.maxStatementsPerConnection=0 torque.dsfactory.order.pool.numHelperThreads=3 torque.dsfactory.order.pool.idleConnectionTestPeriod=600 torque.dsfactory.order.pool.preferredTestQuery=select sysdate from dualtorque.dsfactory.order.connection.driverClass = oracle.jdbc.driver.OracleDriver torque.dsfactory.order.connection.jdbcUrl = jdbc:oracle:thin:@192.168.2.200:1521:BABY_ORDER torque.dsfactory.order.connection.user = scott torque.dsfactory.order.connection.password = tiger3.log4j.properties配置
# ------------------------------------------------------------------------ # # Logging Configuration # # $Id: log4j.properties,v 1.10 2005/07/27 04:25:09 huangxq Exp $ # # ------------------------------------------------------------------------# # If we don't know the logging facility, put it into the # sl.log # log4j.rootLogger = error, root, stdout# # Application debugging # #log4j.category.com.sl = debug, sl log4j.category.com.sl = debug, sl, stdout log4j.additivity.com.sl = false# # torque goes into torque Log # log4j.category.org.apache.torque = debug, torque log4j.additivity.org.apache.torque = false######################################################################## # # Logfile definitions # #########################################################################print out to console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] [%F] %M : %L -- %m%n# # root.log # log4j.appender.root = org.apache.log4j.DailyRollingFileAppender log4j.appender.root.file = D:/logs/fmanage/fmanage_root.log log4j.appender.root.DatePattern='.'yyyy-MM-dd log4j.appender.root.layout = org.apache.log4j.PatternLayout log4j.appender.root.layout.conversionPattern =%d [%-5p] [%F] : %L -- %m%n log4j.appender.root.append = false# # sl.log # log4j.appender.sl = org.apache.log4j.DailyRollingFileAppender log4j.appender.sl.file = D:/logs/fmanage/fmanage_sl.log log4j.appender.sl.DatePattern='.'yyyy-MM-dd log4j.appender.sl.layout = org.apache.log4j.PatternLayout log4j.appender.sl.layout.conversionPattern =%d [%-5p] [%F] : %L -- %m%n log4j.appender.sl.append = true# # torque.log # log4j.appender.torque = org.apache.log4j.DailyRollingFileAppender log4j.appender.torque.file = D:/logs/fmanage/fmanage_torque.log log4j.appender.torque.DatePattern='.'yyyy-MM-dd log4j.appender.torque.layout = org.apache.log4j.PatternLayout log4j.appender.torque.layout.conversionPattern =%d [%-5p] [%F] : %L -- %m%n log4j.appender.torque.append = false4.初始化Torque
InitServer.java
package com.sl;import java.io.InputStream; import java.util.List; import java.util.Properties; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import com.sl.util.DBUtils; import com.workingdogs.village.Record;public class InitServer {private static Logger log;private static final String TORQUE_CONFIG_FILE = "torque.properties";private static final String LOG4J_CONFIG_FILE = "log4j.properties";public static boolean init() {// 初始化boolean flag = true;ClassLoader cl = InitServer.class.getClassLoader();InputStream logIn = null;InputStream dbIn = null;try {logIn = cl.getResourceAsStream(LOG4J_CONFIG_FILE);Properties p = new Properties();p.load(logIn);PropertyConfigurator.configure(p);log = Logger.getLogger(InitServer.class);log.debug("InitServer init() log4j init success ---------------");// 初始化PropertiesConfiguration dbConfig = new PropertiesConfiguration();dbIn = cl.getResourceAsStream(TORQUE_CONFIG_FILE);dbConfig.load(dbIn);DBUtils.init(dbConfig);log.debug("InitServer init() Torque init success ---------------");String testSql = "select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') from dual";String time = null;List<Record> list = DBUtils.query(testSql);if (list != null && list.size() > 0) {Record record = list.get(0);time = record.getValue(1).asString();log.debug("from db init-time: " + time);}} catch (Exception ex) {log.error("InitServer Exception when init() - " + ex);flag = false;} finally {closeInputStream(logIn);closeInputStream(dbIn);}return flag;}private static void closeInputStream(InputStream is) {// 退出前,一定要將文件處理讀寫器關閉try {if (is != null)is.close();is = null;} catch (Exception exx) {log.error(exx);}}}DBUtils.java
package com.sl.util;import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.List; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.apache.torque.util.BasePeer; import com.workingdogs.village.Record; import org.apache.torque.Torque;public class DBUtils {private static Logger log = Logger.getLogger(DBUtils.class.getName());public DBUtils() {}/*** 初始化* * @param dbConfigFile* @return*/public static boolean init(String dbConfigFile) {// 初始化torqueboolean flag = true;try {Torque.init(dbConfigFile);System.out.println("---------- 初始化torque成功---------");} catch (Exception exx) {log.error(exx);flag = false;}return flag;}/*** 初始化* * @param dbConfig* @return*/public static boolean init(Configuration dbConfig) {// 初始化torqueboolean flag = true;try {Torque.init(dbConfig);System.out.println("---------- 初始化torque成功---------");} catch (Exception exx) {log.error(exx);flag = false;}return flag;}/*** 獲取數據庫連接(默認)* * @return*/public static Connection getDBConn() {// 取得數據庫連接Connection conn = null;try {conn = Torque.getConnection();} catch (Exception exx) {log.error(exx);}return conn;}/*** 獲取指定數據庫連接* * @param dbName* @return*/public static Connection getDBConn(String dbName) {// 取得數據庫連接Connection conn = null;try {conn = Torque.getConnection(dbName);} catch (Exception exx) {log.error(exx);}return conn;}/*** 獲取默認數據庫連接,是否支持事務自動提交* * @param autoCommitFlag* @return*/public static Connection getDBConn(boolean autoCommitFlag) {// 取得數據庫連接Connection conn = null;try {conn = Torque.getConnection();setAutoCommit(conn, autoCommitFlag);} catch (Exception exx) {log.error(exx);}return conn;}/*** 獲取指定數據庫連接,是否支持事務自動提交* * @param dbName* @param autoCommitFlag* @return*/public static Connection getDBConn(String dbName, boolean autoCommitFlag) {// 取得數據庫連接Connection conn = null;try {conn = Torque.getConnection(dbName);setAutoCommit(conn, autoCommitFlag);} catch (Exception exx) {log.error(exx);}return conn;}/*** 關閉數據庫連接* * @param conn*/public static void closeDBConn(Connection conn) {// 關閉數據庫連接try {if (conn != null) {setAutoCommit(conn, true);// 無論如何,都應該在連接關閉前,將AutoCommit 設置為// trueTorque.closeConnection(conn);conn = null;}} catch (Exception exx) {log.error(exx);}}/*** 關閉Statement* * @param statement*/public static void closeDBStatement(Statement statement) {// 關閉Statementtry {if (statement != null) {statement.close();statement = null;}} catch (Exception exx) {log.error(exx);}}/*** 關閉Statement,關閉數據庫連接* * @param statement* @param conn*/public static void closeDBObject(Statement statement, Connection conn) {// 關閉StatementcloseDBStatement(statement);// 關閉數據庫連接closeDBConn(conn);}/*** 關閉ResultSet* * @param resultSet*/public static void closeDBResultSet(ResultSet resultSet) {// 關閉ResultSettry {if (resultSet != null) {resultSet.close();resultSet = null;}} catch (Exception exx) {log.error(exx);}}/*** 關閉Statement,關閉ResultSet,關閉數據庫連接* * @param statement* @param resultSet* @param conn* @param autoCommitFlag*/public static void closeDBObject(Statement statement, ResultSet resultSet, Connection conn) {// 關閉StatementcloseDBStatement(statement);// 關閉ResultSetcloseDBResultSet(resultSet);// 關閉數據庫鏈接closeDBConn(conn);}/*** 提交事務* * @param conn*/public static void commit(Connection conn) {try {if (conn != null) {if (conn.getMetaData().supportsTransactions() && conn.getAutoCommit() == false) {conn.commit();conn.setAutoCommit(true);}}} catch (Exception exx) {log.error(exx);}}/*** 回滾事務* * @param conn*/public static void rollback(Connection conn) {try {if (conn != null) {if (conn.getMetaData().supportsTransactions() && conn.getAutoCommit() == false) {conn.rollback();conn.setAutoCommit(true);}}} catch (Exception ee) {log.error(ee);}}/*** 設置是否自動提交事務* * @param conn* @param autoCommitFlag*/public static void setAutoCommit(Connection conn, boolean autoCommitFlag) {try {if (conn.getMetaData().supportsTransactions()) {conn.setAutoCommit(autoCommitFlag);}} catch (Exception e) {log.error(e);}}/*** 查詢返回所有記錄* * @param querySql* @return*/@SuppressWarnings("unchecked")public static List<Record> query(String querySql) {List<Record> results = null;try {results = BasePeer.executeQuery(querySql);} catch (Exception ee) {results = null;log.error(ee);}return results;}/*** 查詢 * singleRecord = true 表示只返回一條記錄 * singleRecord = false 表示返回所有記錄* * @param conn* @param singleRecord* @param querySql* @return*/@SuppressWarnings("unchecked")public static List<Record> query(Connection conn, boolean singleRecord, String querySql) {List<Record> results = null;try {if (conn != null) {results = BasePeer.executeQuery(querySql, singleRecord, conn);}} catch (Exception ee) {results = null;log.error(ee);} finally {closeDBConn(conn);}return results;}/*** 查詢返回所有記錄* * @param conn* @param querySql* @return*/public static List<Record> query(Connection conn, String querySql) {List<Record> results = null;boolean singleRecord = false;results = query(conn, singleRecord, querySql);return results;}/*** 查詢指定配置的數據庫,返回所有記錄* * @param dbName* @param querySql* @return*/public static List<Record> query(String dbName, String querySql) {List<Record> results = null;try {Connection conn = DBUtils.getDBConn(dbName);if (conn != null) {results = query(conn, querySql);}} catch (Exception ee) {results = null;log.error(ee);}return results;}/*** 添加或更新數據庫記錄* * @param insertOrUpdateSql* @return*/public static int insertOrUpdate(String insertOrUpdateSql) {int results = -1;try {results = BasePeer.executeStatement(insertOrUpdateSql);} catch (Exception ee) {results = -1;log.error(ee);}return results;}/*** 添加或更新數據庫記錄* * @param conn* @param insertOrUpdateSql* @return*/public static int insertOrUpdate(Connection conn, String insertOrUpdateSql) {int results = -1;try {if (conn != null) {results = BasePeer.executeStatement(insertOrUpdateSql, conn);}} catch (Exception ee) {results = -1;log.error(ee);} finally {closeDBConn(conn);}return results;}}5.使用
查詢默認數據庫可直接使用List<Record> list = DBUtils.query(querySql);
也可以List<Record> list = DBUtils.query("bookstore", querySql);
查詢指定的數據庫使用List<Record> list = DBUtils.query("order", querySql);
注:“order”是自定義的數據庫名,可以和真實數據庫名不一樣,作為Torque的數據庫標識。
本文參考:
http://www.blogjava.net/fanyingjie/archive/2008/05/22/202114.html
總結
以上是生活随笔為你收集整理的Apache Torque连接多个数据库及其使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二年级上册计算题_2015年二年级上册数
- 下一篇: 【无标题】Android studio连