Apache
Torque是一個使用關(guān)系數(shù)據(jù)庫作為存儲手段的Java應(yīng)用程序持久化工具,是 Apache 的公開源代碼項目,
Torque是一個開源項目,由Web應(yīng)用程序框架Jakarta Apache Turbine發(fā)展而來,但現(xiàn)在已完全獨立于Turbine。
Torque 主要包含兩部分:一部分是 Generator,它可以使用xml文件,產(chǎn)生應(yīng)用程序需要的所有數(shù)據(jù)庫資源,包括 sql 和 java 文件;另外一部分是 Runtime,提供使用這些代碼訪問數(shù)據(jù)庫的運行時環(huán)境。
torque作為orm,我一般是自己手工編寫xml文件,通過xml文件,生成sql腳本和java對象文件,但由于在實際項目過程中,很難做到表結(jié)構(gòu)不變動,很多時間需要花在xml文件的維護和java對象文件的更換上,在幾個實際項目中使用過后,就放棄了。放棄的原因主要有:1、項目組的兄弟多數(shù)比較抵制操作java對象來進行數(shù)據(jù)庫,因為他們看不到自己比較熟悉的sql了;2、使用orm工具多少需要些時間來學(xué)習(xí)工具的使用,雖然相對于現(xiàn)在hibernate,
torque還是比較簡單的;3、在項目中,也很難做到數(shù)據(jù)庫設(shè)計不變化,另外舊就是我現(xiàn)在所在公司大量使用oracle存儲過程;4、在大多數(shù)時候,項目總是由最少的人,干盡可能多的事情,所以在很多時候,你不得不放棄一些所謂的技術(shù)和理念,用最短的時間將事情搞定,你才能獲得上司的認可。尤其在我目前所在公司,一個千萬級別的項目,也僅僅是3~5個人來完成,作為項目經(jīng)理,除了要做數(shù)據(jù)庫設(shè)計、存儲過程編寫、框架
搭建、新人培訓(xùn)(因為3~5個人里面也許就你一個是有經(jīng)驗的人)、硬件設(shè)備收貨、機器上架、網(wǎng)絡(luò)打通(如果你還會調(diào)試路由器,這個事情也屬于你來搞定的范疇)協(xié)調(diào)、各種外系統(tǒng)接口梳理和定義、外系統(tǒng)相關(guān)公司協(xié)調(diào),呵呵,我經(jīng)常戲虐公司的項目經(jīng)理是十項全能選手,因為你的上司還要求你要有銷售意識。
扯遠了,如何使用
torque作為orm我就不寫了,我現(xiàn)在一般使用
torque作為數(shù)據(jù)庫訪問工具,如何將
torque引入你的系統(tǒng)(非web應(yīng)用,獨立應(yīng)用程序),以oracle作為實際例子:
第一步:引入包
classes12.jar
log4j-1.2.15.jar
commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-configuration-1.1.jar
commons-dbcp-1.2.2.jar(如果你還在使用commons-dbcp-1.2.2.jar以下版本作為數(shù)據(jù)庫連接池,都請更新到commons-dbcp-1.2.2.jar)
commons-lang-2.1.jar
commons-logging-1.0.4.jar
commons-pool-1.2.jar
commons-discovery-0.2.jar
torque-3.2.jar
village-2.0-dev-20030825.jar
第二步:配置
torque.properties 和 log4j.properties ,配置文件我一般放在classes目錄下
1、
torque.properties
# -------------------------------------------------------------------
# $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 = d:/work/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=mydb
torque.database.mydb.adapter=oracle
# # Using commons-dbcp
torque.dsfactory.mydb.factory=org.apache.
torque.dsfactory.SharedPoolDataSourceFactory
torque.dsfactory.mydb.pool.maxIdle=8
torque.dsfactory.mydb.pool.maxActive=10
torque.dsfactory.mydb.pool.testOnBorrow=true
torque.dsfactory.mydb.pool.validationQuery=select * from dual
torque.dsfactory.mydb.connection.driver = oracle.jdbc.driver.OracleDriver
torque.dsfactory.mydb.connection.url = jdbc:oracle:thin:@192.168.12.186:1521:mydb
torque.dsfactory.mydb.connection.user = myname
torque.dsfactory.mydb.connection.password = mypwd
# 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
2、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
# ideal.log
#
log4j.rootLogger = error, stdout
#
# Application debugging
#
log4j.category.com.yh = DEBUG, stdout,ideal
log4j.additivity.com.ideal = false
#
#
torque goes into
torque Log
#
log4j.category.org.apache.
torque = ERROR,
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.RollingFileAppender
log4j.appender.root.MaxFileSize=2000KB
# Keep one backup file
log4j.appender.root.MaxBackupIndex=10
#log4j.appender.root.file = ./logs/root.log
log4j.appender.root.layout = org.apache.log4j.PatternLayout
log4j.appender.root.layout.conversionPattern =%d [%-5p] [%F] : %L -- %m%n
log4j.appender.root.append = false
#
# yh.log
#
log4j.appender.yh = org.apache.log4j.RollingFileAppender
log4j.appender.yh.MaxFileSize=2000KB
# Keep one backup file
log4j.appender.yh.MaxBackupIndex=10
log4j.appender.yh.file = ./logs/yh.log
log4j.appender.yh.layout = org.apache.log4j.PatternLayout
log4j.appender.yh.layout.conversionPattern =%d [%-5p] [%F] : %L -- %m%n
log4j.appender.ideal.append = false
#
#
torque.log
#
log4j.appender.
torque = org.apache.log4j.RollingFileAppender
log4j.appender.
torque.MaxFileSize=2000KB
# Keep one backup file
log4j.appender.
torque.MaxBackupIndex=10
#log4j.appender.
torque.file = ./logs/
torque.log
log4j.appender.
torque.layout = org.apache.log4j.PatternLayout
log4j.appender.
torque.layout.conversionPattern =%d [%-5p] [%F] : %L -- %m%n
log4j.appender.
torque.append = false
第三步:初始化
torque
InitServer.java
- package com.yh.core.socket.server;
-
- 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.yh.util.DBUtils;
- import com.yh.util.FileUtils;
- import com.workingdogs.village.Record;
-
-
-
-
-
-
-
-
- public class InitServer {
-
- private static Logger log ;
- private static final String <SPAN class=hilite1><SPAN class=hilite1>TORQUE</SPAN></SPAN>_CONFIG_FILE = "<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>.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(<SPAN class=hilite1><SPAN class=hilite1>TORQUE</SPAN></SPAN>_CONFIG_FILE);
- dbConfig.load(dbIn);
- DBUtils.init(dbConfig);
- log.debug("InitServer init() <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN> init success ---------------" );
- String testSql = "select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') from dual";
- String time = null;
- List list = DBUtils.query(testSql);
- if(list!=null&&list.size()>0){
- Record 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
- {
- FileUtils.closeInputStream(logIn);
- FileUtils.closeInputStream(dbIn);
- }
- return flag;
- }
-
- }
package com.yh.core.socket.server;
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.yh.util.DBUtils;
import com.yh.util.FileUtils;
import com.workingdogs.village.Record;
/**
* @author tylzhuang
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
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 list = DBUtils.query(testSql);
if(list!=null&&list.size()>0){
Record 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
{
FileUtils.closeInputStream(logIn);
FileUtils.closeInputStream(dbIn);
}
return flag;
}
}
DBUtils.java
-
- package com.yh.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.<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>.<SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>;
- import org.apache.<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>.util.BasePeer;
-
-
-
-
-
-
-
- public class DBUtils {
- private static Logger log = Logger.getLogger(DBUtils.class.getName());
-
- public DBUtils() {
- }
-
- public static boolean init(String dbConfigFile) {
-
- boolean flag = true;
- try {
- <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.init(dbConfigFile);
- System.out.println("---------- 初始化<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>成功---------");
- } catch (Exception exx) {
- log.error(exx);
- flag = false;
- }
- return flag;
- }
-
- public static boolean init(Configuration dbConfig) {
-
- boolean flag = true;
- try {
- <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.init(dbConfig);
- System.out.println("---------- 初始化<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>成功---------");
- } catch (Exception exx) {
- log.error(exx);
- flag = false;
- }
- return flag;
- }
-
- public static Connection getDBConn() {
-
- Connection conn = null;
- try {
- conn = <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.getConnection();
- } catch (Exception exx) {
- log.error(exx);
- }
- return conn;
- }
-
- public static Connection getDBConn(String dbName) {
-
- Connection conn = null;
- try {
- conn = <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.getConnection(dbName);
- } catch (Exception exx) {
- log.error(exx);
- }
- return conn;
- }
-
- public static Connection getDBConn(boolean autoCommitFlag) {
-
- Connection conn = null;
- try {
- conn = <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.getConnection();
- setAutoCommit(conn , autoCommitFlag);
- } catch (Exception exx) {
- log.error(exx);
- }
- return conn;
- }
-
- public static Connection getDBConn(String dbName, boolean autoCommitFlag) {
-
- Connection conn = null;
- try {
- conn = <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.getConnection(dbName);
- setAutoCommit(conn , autoCommitFlag);
- } catch (Exception exx) {
- log.error(exx);
- }
- return conn;
- }
-
- public static void closeDBConn(Connection conn) {
-
- try {
- if (conn != null) {
- setAutoCommit(conn , true);
-
- <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.closeConnection(conn);
- conn = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
- }
-
- public static void closeDBConn(Connection conn, boolean autoCommitFlag) {
-
- try {
- if (conn != null) {
- setAutoCommit(conn , true);
-
- <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.closeConnection(conn);
- conn = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
- }
-
- public static void closeDBStatement(Statement s) {
-
- try {
- if (s != null) {
- s.close();
- s = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
- }
-
- public static void closeDBObject(Statement s, Connection conn) {
-
- try {
- if (s != null) {
- s.close();
- s = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
-
- try {
- if (conn != null) {
- setAutoCommit(conn , true);
-
- <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.closeConnection(conn);
- conn = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
- }
- public static void closeDBResultSet(ResultSet r) {
-
- try {
- if (r != null) {
- r.close();
- r = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
- }
- public static void closeDBObject(Statement s, Connection conn,
- boolean autoCommitFlag) {
-
- try {
- if (s != null) {
- s.close();
- s = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
-
-
- try {
- if (conn != null) {
- setAutoCommit(conn , true);
-
- <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.closeConnection(conn);
- conn = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
- }
- public static void closeDBObject(Statement s, ResultSet r ,Connection conn,
- boolean autoCommitFlag) {
-
- try {
- if (s != null) {
- s.close();
- s = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
-
- try {
- if (r != null) {
- r.close();
- r = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
-
- try {
- if (conn != null) {
- setAutoCommit(conn , true);
-
- <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.closeConnection(conn);
- conn = null;
- }
- } catch (Exception exx) {
- log.error(exx);
- }
- }
-
- 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);
- }
- }
-
- 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);
- }
- }
- public static void setAutoCommit(Connection conn , boolean autoCommitFlag)
- {
- try
- {
- if (conn.getMetaData().supportsTransactions())
- {
- conn.setAutoCommit(autoCommitFlag);
- }
- }
- catch (Exception e)
- {
- log.error(e);
- }
- }
-
- public static List query(String querySql) {
- List results = null;
- try {
- results = BasePeer.executeQuery(querySql);
- } catch (Exception ee) {
- results = null;
- log.error(ee);
- }
- return results;
- }
-
-
- public static List query(Connection conn, boolean singleRecord,
- String querySql) {
- List results = null;
- try {
- if (conn != null) {
- results = BasePeer.executeQuery(querySql, singleRecord, conn);
- }
- } catch (Exception ee) {
- results = null;
- log.error(ee);
- }
- return results;
- }
-
-
- public static List query(Connection conn,
- String querySql) {
- List results = null;
- boolean singleRecord = false;
- results = query(conn , singleRecord , querySql);
- return results;
- }
-
-
- public static List query(String dbName ,String querySql) {
- List results = null;
- try {
- Connection conn = DBUtils.getDBConn(dbName);
- if(conn != null)
- results = query(conn , querySql);
- else
- results = null;
- } catch (Exception ee) {
- results = null;
- log.error(ee);
- }
- return results;
- }
-
- public static int insertOrUpdate(String insertSql) {
- int results = -1;
- try {
- results = BasePeer.executeStatement(insertSql);
- } catch (Exception ee) {
- results = -1;
- log.error(ee);
- }
- return results;
- }
-
- public static int insertOrUpdate(Connection conn, String insertSql) {
- int results = -1;
- try {
- if (conn != null) {
- results = BasePeer.executeStatement(insertSql, conn);
- }
- } catch (Exception ee) {
- results = -1;
- log.error(ee);
- }
- return results;
- }
-
-
-
- }
package com.yh.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.Torque;
import org.apache.torque.util.BasePeer;
/**
* @author tylzhuang
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class DBUtils {
private static Logger log = Logger.getLogger(DBUtils.class.getName());
public DBUtils() {
}
public static boolean init(String dbConfigFile) {
// 初始化torque
boolean flag = true;
try {
Torque.init(dbConfigFile);
System.out.println("---------- 初始化torque成功---------");
} catch (Exception exx) {
log.error(exx);
flag = false;
}
return flag;
}
public static boolean init(Configuration dbConfig) {
// 初始化torque
boolean flag = true;
try {
Torque.init(dbConfig);
System.out.println("---------- 初始化torque成功---------");
} catch (Exception exx) {
log.error(exx);
flag = false;
}
return flag;
}
public static Connection getDBConn() {
// 取得數(shù)據(jù)庫鏈接
Connection conn = null;
try {
conn = Torque.getConnection();
} catch (Exception exx) {
log.error(exx);
}
return conn;
}
public static Connection getDBConn(String dbName) {
// 取得數(shù)據(jù)庫鏈接
Connection conn = null;
try {
conn = Torque.getConnection(dbName);
} catch (Exception exx) {
log.error(exx);
}
return conn;
}
public static Connection getDBConn(boolean autoCommitFlag) {
// 取得數(shù)據(jù)庫鏈接
Connection conn = null;
try {
conn = Torque.getConnection();
setAutoCommit(conn , autoCommitFlag);
} catch (Exception exx) {
log.error(exx);
}
return conn;
}
public static Connection getDBConn(String dbName, boolean autoCommitFlag) {
// 取得數(shù)據(jù)庫鏈接
Connection conn = null;
try {
conn = Torque.getConnection(dbName);
setAutoCommit(conn , autoCommitFlag);
} catch (Exception exx) {
log.error(exx);
}
return conn;
}
public static void closeDBConn(Connection conn) {
// 關(guān)閉數(shù)據(jù)庫鏈接
try {
if (conn != null) {
setAutoCommit(conn , true);// 無論如何,都應(yīng)該在連接關(guān)閉前,將AutoCommit 設(shè)置為
// true
Torque.closeConnection(conn);
conn = null;
}
} catch (Exception exx) {
log.error(exx);
}
}
public static void closeDBConn(Connection conn, boolean autoCommitFlag) {
// 關(guān)閉數(shù)據(jù)庫鏈接
try {
if (conn != null) {
setAutoCommit(conn , true);// 無論傳什么值,都應(yīng)該在連接關(guān)閉前,將AutoCommit 設(shè)置為
// true
Torque.closeConnection(conn);
conn = null;
}
} catch (Exception exx) {
log.error(exx);
}
}
public static void closeDBStatement(Statement s) {
// 關(guān)閉Statement
try {
if (s != null) {
s.close();
s = null;
}
} catch (Exception exx) {
log.error(exx);
}
}
public static void closeDBObject(Statement s, Connection conn) {
// 關(guān)閉Statement
try {
if (s != null) {
s.close();
s = null;
}
} catch (Exception exx) {
log.error(exx);
}
// 關(guān)閉數(shù)據(jù)庫鏈接
try {
if (conn != null) {
setAutoCommit(conn , true);// 無論如何,都應(yīng)該在連接關(guān)閉前,將AutoCommit 設(shè)置為
// true
Torque.closeConnection(conn);
conn = null;
}
} catch (Exception exx) {
log.error(exx);
}
}
public static void closeDBResultSet(ResultSet r) {
// 關(guān)閉ResultSet
try {
if (r != null) {
r.close();
r = null;
}
} catch (Exception exx) {
log.error(exx);
}
}
public static void closeDBObject(Statement s, Connection conn,
boolean autoCommitFlag) {
// 關(guān)閉Statement
try {
if (s != null) {
s.close();
s = null;
}
} catch (Exception exx) {
log.error(exx);
}
// 關(guān)閉數(shù)據(jù)庫鏈接
try {
if (conn != null) {
setAutoCommit(conn , true);// 無論傳什么值,都應(yīng)該在連接關(guān)閉前,將AutoCommit 設(shè)置為
// true
Torque.closeConnection(conn);
conn = null;
}
} catch (Exception exx) {
log.error(exx);
}
}
public static void closeDBObject(Statement s, ResultSet r ,Connection conn,
boolean autoCommitFlag) {
// 關(guān)閉Statement
try {
if (s != null) {
s.close();
s = null;
}
} catch (Exception exx) {
log.error(exx);
}
// 關(guān)閉ResultSet
try {
if (r != null) {
r.close();
r = null;
}
} catch (Exception exx) {
log.error(exx);
}
// 關(guān)閉數(shù)據(jù)庫鏈接
try {
if (conn != null) {
setAutoCommit(conn , true);// 無論傳什么值,都應(yīng)該在連接關(guān)閉前,將AutoCommit 設(shè)置為
// true
Torque.closeConnection(conn);
conn = null;
}
} catch (Exception exx) {
log.error(exx);
}
}
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);
}
}
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);
}
}
public static void setAutoCommit(Connection conn , boolean autoCommitFlag)
{
try
{
if (conn.getMetaData().supportsTransactions())
{
conn.setAutoCommit(autoCommitFlag);
}
}
catch (Exception e)
{
log.error(e);
}
}
public static List query(String querySql) {
List results = null;
try {
results = BasePeer.executeQuery(querySql);
} catch (Exception ee) {
results = null;
log.error(ee);
}
return results;
}
// singleRecord = true 表示只返回一條記錄
// singleRecord = false 表示返回所有記錄
public static List query(Connection conn, boolean singleRecord,
String querySql) {
List results = null;
try {
if (conn != null) {
results = BasePeer.executeQuery(querySql, singleRecord, conn);
}
} catch (Exception ee) {
results = null;
log.error(ee);
}
return results;
}
// singleRecord = true 表示只返回一條記錄
// singleRecord = false 表示返回所有記錄
public static List query(Connection conn,
String querySql) {
List results = null;
boolean singleRecord = false;
results = query(conn , singleRecord , querySql);
return results;
}
//查詢數(shù)據(jù)庫指定配置的數(shù)據(jù)庫
public static List query(String dbName ,String querySql) {
List results = null;
try {
Connection conn = DBUtils.getDBConn(dbName);
if(conn != null)
results = query(conn , querySql);
else
results = null;
} catch (Exception ee) {
results = null;
log.error(ee);
}
return results;
}
public static int insertOrUpdate(String insertSql) {
int results = -1;
try {
results = BasePeer.executeStatement(insertSql);
} catch (Exception ee) {
results = -1;
log.error(ee);
}
return results;
}
public static int insertOrUpdate(Connection conn, String insertSql) {
int results = -1;
try {
if (conn != null) {
results = BasePeer.executeStatement(insertSql, conn);
}
} catch (Exception ee) {
results = -1;
log.error(ee);
}
return results;
}
}
這里寫如何在web應(yīng)用里使用torque,以struts為例:
第一步和第二步參考如何使用 apache torque (一)
第三步:初始化torque ,我采用擴展 ActionServlet.java 實現(xiàn)
ExtendActionServlet.java
- package com.yh.web.servlet;
-
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Properties;
- import java.util.List;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import org.apache.commons.configuration.PropertiesConfiguration;
- import org.apache.log4j.Logger;
- import org.apache.log4j.PropertyConfigurator;
- import org.apache.struts.action.ActionServlet;
-
- import com.yh.util.DBUtils;
- import com.yh.util.FileUtils;
- import com.workingdogs.village.Record;
-
-
-
-
-
- public class ExtendActionServlet extends ActionServlet {
- private static Logger log;
-
- private static final String LOG4J_CONFIG_FILE = "log4j.properties";
-
- private static final String TORQUE_CONFIG_FILE = "torque.properties";
-
-
- public static PropertiesConfiguration commonConfig = null;
-
-
- public void init() throws ServletException {
- synchronized (this.getClass()) {
- super.init();
- ClassLoader cl = this.getClass().getClassLoader();
- InputStream logIn = null;
- InputStream dbIn = null;
- try {
- logIn = cl.getResourceAsStream(LOG4J_CONFIG_FILE);
- Properties p = new Properties();
- p.load(logIn);
- PropertyConfigurator.configure(p);
- System.out.println("log4j init success -----------------");
-
- log = Logger.getLogger(ExtendActionServlet.class);
-
- log.debug("log4j init success------------" );
-
- dbIn = cl.getResourceAsStream(TORQUE_CONFIG_FILE);
- PropertiesConfiguration dbConfig = new PropertiesConfiguration();
- dbConfig.load(dbIn);
- DBUtils.init(dbConfig);
- System.out.println("torque init success----------");
-
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- finally
- {
- FileUtils.closeInputStream(logIn);
- FileUtils.closeInputStream(dbIn);
- }
- System.out.println("init() Ready to Rumble!");
- }
- }
-
-
- public void destroy() {
- super.destroy();
- }
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
-
- process(request, response);
-
- }
-
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
-
- process(request, response);
-
- }
-
- protected void process(HttpServletRequest request,
- HttpServletResponse response) throws IOException, ServletException {
- super.process(request, response);
- }
- }
package com.yh.web.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.struts.action.ActionServlet;
import com.yh.util.DBUtils;
import com.yh.util.FileUtils;
import com.workingdogs.village.Record;
/**
* @author tylzhuang
*/
public class ExtendActionServlet extends ActionServlet {
private static Logger log;
private static final String LOG4J_CONFIG_FILE = "log4j.properties";
private static final String TORQUE_CONFIG_FILE = "torque.properties";
/** Our internal configuration object */
public static PropertiesConfiguration commonConfig = null;
// Initialize global variables
public void init() throws ServletException {
synchronized (this.getClass()) {
super.init();
ClassLoader cl = this.getClass().getClassLoader();
InputStream logIn = null;
InputStream dbIn = null;
try {
logIn = cl.getResourceAsStream(LOG4J_CONFIG_FILE);
Properties p = new Properties();
p.load(logIn);
PropertyConfigurator.configure(p);
System.out.println("log4j init success -----------------");
//System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.Log4JLogger");
log = Logger.getLogger(ExtendActionServlet.class);
log.debug("log4j init success------------" );
dbIn = cl.getResourceAsStream(TORQUE_CONFIG_FILE);
PropertiesConfiguration dbConfig = new PropertiesConfiguration();
dbConfig.load(dbIn);
DBUtils.init(dbConfig);
System.out.println("torque init success----------");
} catch (Exception ex) {
ex.printStackTrace();
}
finally
{
FileUtils.closeInputStream(logIn);
FileUtils.closeInputStream(dbIn);
}
System.out.println("init() Ready to Rumble!");
}
}
// Clean up resources
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}
protected void process(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
super.process(request, response);
}
}