JAVA—咖啡馆

——欢迎访问rogerfan的博客,常来《JAVA——咖啡馆》坐坐,喝杯浓香的咖啡,彼此探讨一下JAVA技术,交流工作经验,分享JAVA带来的快乐!本网站部分转载文章,如果有版权问题请与我联系。

BlogJava 首页 新随笔 联系 聚合 管理
  447 Posts :: 145 Stories :: 368 Comments :: 0 Trackbacks
Apache Torque是一个使用关系数据库作为存储手段的Java应用程序持久化工具,是 Apache 的公开源代码项目,Torque是一个开源项目,由Web应用程序框架Jakarta Apache Turbine发展而来,但现在已完全独立于Turbine。 Torque 主要包含两部分:一部分是 Generator,它可以使用xml文件,产生应用程序需要的所有数据库资源,包括 sql 和 java 文件;另外一部分是 Runtime,提供使用这些代码访问数据库的运行时环境。

torque作为orm,我一般是自己手工编写xml文件,通过xml文件,生成sql脚本和java对象文件,但由于在实际项目过程中,很难做到表结构不变动,很多时间需要花在xml文件的维护和java对象文件的更换上,在几个实际项目中使用过后,就放弃了。放弃的原因主要有:1、项目组的兄弟多数比较抵制操作java对象来进行数据库,因为他们看不到自己比较熟悉的sql了;2、使用orm工具多少需要些时间来学习工具的使用,虽然相对于现在hibernate,torque还是比较简单的;3、在项目中,也很难做到数据库设计不变化,另外旧就是我现在所在公司大量使用oracle存储过程;4、在大多数时候,项目总是由最少的人,干尽可能多的事情,所以在很多时候,你不得不放弃一些所谓的技术和理念,用最短的时间将事情搞定,你才能获得上司的认可。尤其在我目前所在公司,一个千万级别的项目,也仅仅是3~5个人来完成,作为项目经理,除了要做数据库设计、存储过程编写、框架搭建、新人培训(因为3~5个人里面也许就你一个是有经验的人)、硬件设备收货、机器上架、网络打通(如果你还会调试路由器,这个事情也属于你来搞定的范畴)协调、各种外系统接口梳理和定义、外系统相关公司协调,呵呵,我经常戏虐公司的项目经理是十项全能选手,因为你的上司还要求你要有销售意识。
扯远了,如何使用torque作为orm我就不写了,我现在一般使用torque作为数据库访问工具,如何将torque引入你的系统(非web应用,独立应用程序),以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以下版本作为数据库连接池,都请更新到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
Java代码
  1. package com.yh.core.socket.server;   
  2.   
  3. import java.io.InputStream;   
  4. import java.util.List;   
  5. import java.util.Properties;   
  6.   
  7. import org.apache.commons.configuration.PropertiesConfiguration;   
  8. import org.apache.log4j.Logger;   
  9. import org.apache.log4j.PropertyConfigurator;   
  10.   
  11. import com.yh.util.DBUtils;   
  12. import com.yh.util.FileUtils;   
  13. import com.workingdogs.village.Record;   
  14.   
  15. /**  
  16.  * @author tylzhuang  
  17.  *   
  18.  * TODO To change the template for this generated type comment go to Window -  
  19.  * Preferences - Java - Code Style - Code Templates  
  20.  */  
  21.   
  22. public class InitServer {   
  23.        
  24.     private static Logger log ;   
  25.     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";   
  26.     private static final String LOG4J_CONFIG_FILE = "log4j.properties";   
  27.     public static boolean init() {   
  28.         // 初始化   
  29.         boolean flag = true;   
  30.         ClassLoader cl = InitServer.class.getClassLoader();   
  31.         InputStream logIn = null;   
  32.         InputStream dbIn = null;   
  33.   
  34.         try {   
  35.                
  36.             logIn = cl.getResourceAsStream(LOG4J_CONFIG_FILE);   
  37.             Properties p = new Properties();   
  38.             p.load(logIn);   
  39.             PropertyConfigurator.configure(p);     
  40.             log = Logger.getLogger(InitServer.class);   
  41.             log.debug("InitServer init() log4j init success ---------------" );   
  42.                
  43.                
  44.             //初始化   
  45.             PropertiesConfiguration dbConfig = new PropertiesConfiguration();   
  46.             dbIn = cl.getResourceAsStream(<SPAN class=hilite1><SPAN class=hilite1>TORQUE</SPAN></SPAN>_CONFIG_FILE);   
  47.             dbConfig.load(dbIn);   
  48.             DBUtils.init(dbConfig);   
  49.             log.debug("InitServer init() <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN> init success ---------------" );   
  50.             String testSql = "select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') from dual";   
  51.             String time = null;   
  52.             List list = DBUtils.query(testSql);   
  53.             if(list!=null&&list.size()>0){   
  54.                 Record record = (Record) list.get(0);   
  55.                 time = record.getValue(1).asString();   
  56.                 log.debug("from db init-time: "+time);       
  57.             }   
  58.                
  59.                
  60.         }    
  61.         catch (Exception ex)    
  62.         {   
  63.             log.error("InitServer Exception when init() - "+ex);   
  64.             flag = false;   
  65.         }   
  66.         finally  
  67.         {   
  68.              FileUtils.closeInputStream(logIn);   
  69.              FileUtils.closeInputStream(dbIn);   
  70.         }   
  71.         return flag;   
  72.     }   
  73.   
  74. }  

DBUtils.java
Java代码
  1.   
  2. package com.yh.util;   
  3.   
  4. import java.sql.Connection;   
  5. import java.sql.ResultSet;   
  6. import java.sql.Statement;   
  7. import java.util.List;   
  8.   
  9. import org.apache.commons.configuration.Configuration;   
  10. import org.apache.log4j.Logger;   
  11. import org.apache.<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>.<SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>;   
  12. import org.apache.<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>.util.BasePeer;   
  13.   
  14. /**  
  15.  * @author tylzhuang  
  16.  *   
  17.  * TODO To change the template for this generated type comment go to Window -  
  18.  * Preferences - Java - Code Style - Code Templates  
  19.  */  
  20. public class DBUtils {   
  21.     private static Logger log = Logger.getLogger(DBUtils.class.getName());   
  22.   
  23.     public DBUtils() {   
  24.     }   
  25.   
  26.     public static boolean init(String dbConfigFile) {   
  27.         // 初始化<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>   
  28.         boolean flag = true;   
  29.         try {   
  30.             <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.init(dbConfigFile);   
  31.             System.out.println("---------- 初始化<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>成功---------");   
  32.         } catch (Exception exx) {   
  33.             log.error(exx);   
  34.             flag = false;   
  35.         }   
  36.         return flag;   
  37.     }   
  38.   
  39.     public static boolean init(Configuration dbConfig) {   
  40.         // 初始化<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>   
  41.         boolean flag = true;   
  42.         try {   
  43.             <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.init(dbConfig);   
  44.             System.out.println("---------- 初始化<SPAN class=hilite1><SPAN class=hilite1>torque</SPAN></SPAN>成功---------");   
  45.         } catch (Exception exx) {   
  46.             log.error(exx);   
  47.             flag = false;   
  48.         }   
  49.         return flag;   
  50.     }   
  51.   
  52.     public static Connection getDBConn() {   
  53.         // 取得数据库链接   
  54.         Connection conn = null;   
  55.         try {   
  56.             conn = <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.getConnection();   
  57.         } catch (Exception exx) {   
  58.             log.error(exx);   
  59.         }   
  60.         return conn;   
  61.     }   
  62.   
  63.     public static Connection getDBConn(String dbName) {   
  64.         // 取得数据库链接   
  65.         Connection conn = null;   
  66.         try {   
  67.             conn = <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.getConnection(dbName);   
  68.         } catch (Exception exx) {   
  69.             log.error(exx);   
  70.         }   
  71.         return conn;   
  72.     }   
  73.   
  74.     public static Connection getDBConn(boolean autoCommitFlag) {   
  75.         // 取得数据库链接   
  76.         Connection conn = null;   
  77.         try {   
  78.             conn = <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.getConnection();   
  79.             setAutoCommit(conn , autoCommitFlag);   
  80.         } catch (Exception exx) {   
  81.             log.error(exx);   
  82.         }   
  83.         return conn;   
  84.     }   
  85.   
  86.     public static Connection getDBConn(String dbName, boolean autoCommitFlag) {   
  87.         // 取得数据库链接   
  88.         Connection conn = null;   
  89.         try {   
  90.             conn = <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.getConnection(dbName);   
  91.             setAutoCommit(conn , autoCommitFlag);   
  92.         } catch (Exception exx) {   
  93.             log.error(exx);   
  94.         }   
  95.         return conn;   
  96.     }   
  97.   
  98.     public static void closeDBConn(Connection conn) {   
  99.         // 关闭数据库链接   
  100.         try {   
  101.             if (conn != null) {   
  102.                 setAutoCommit(conn , true);// 无论如何,都应该在连接关闭前,将AutoCommit 设置为   
  103.                 // true   
  104.                 <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.closeConnection(conn);   
  105.                 conn = null;   
  106.             }   
  107.         } catch (Exception exx) {   
  108.             log.error(exx);   
  109.         }   
  110.     }   
  111.   
  112.     public static void closeDBConn(Connection conn, boolean autoCommitFlag) {   
  113.         // 关闭数据库链接   
  114.         try {   
  115.             if (conn != null) {   
  116.                 setAutoCommit(conn , true);// 无论传什么值,都应该在连接关闭前,将AutoCommit 设置为   
  117.                 // true   
  118.                 <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.closeConnection(conn);   
  119.                 conn = null;   
  120.             }   
  121.         } catch (Exception exx) {   
  122.             log.error(exx);   
  123.         }   
  124.     }   
  125.   
  126.     public static void closeDBStatement(Statement s) {   
  127.         // 关闭Statement   
  128.         try {   
  129.             if (s != null) {   
  130.                 s.close();   
  131.                 s = null;   
  132.             }   
  133.         } catch (Exception exx) {   
  134.             log.error(exx);   
  135.         }   
  136.     }   
  137.   
  138.     public static void closeDBObject(Statement s, Connection conn) {   
  139.         // 关闭Statement   
  140.         try {   
  141.             if (s != null) {   
  142.                 s.close();   
  143.                 s = null;   
  144.             }   
  145.         } catch (Exception exx) {   
  146.             log.error(exx);   
  147.         }   
  148.         // 关闭数据库链接   
  149.         try {   
  150.             if (conn != null) {   
  151.                 setAutoCommit(conn , true);// 无论如何,都应该在连接关闭前,将AutoCommit 设置为   
  152.                 // true   
  153.                 <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.closeConnection(conn);   
  154.                 conn = null;   
  155.             }   
  156.         } catch (Exception exx) {   
  157.             log.error(exx);   
  158.         }   
  159.     }   
  160.     public static void closeDBResultSet(ResultSet r) {   
  161.         // 关闭ResultSet   
  162.         try {   
  163.             if (r != null) {   
  164.                 r.close();   
  165.                 r = null;   
  166.             }   
  167.         } catch (Exception exx) {   
  168.             log.error(exx);   
  169.         }          
  170.     }      
  171.     public static void closeDBObject(Statement s, Connection conn,   
  172.             boolean autoCommitFlag) {   
  173.         // 关闭Statement   
  174.         try {   
  175.             if (s != null) {   
  176.                 s.close();   
  177.                 s = null;   
  178.             }   
  179.         } catch (Exception exx) {   
  180.             log.error(exx);   
  181.         }   
  182.        
  183.         // 关闭数据库链接   
  184.         try {   
  185.             if (conn != null) {   
  186.                 setAutoCommit(conn , true);// 无论传什么值,都应该在连接关闭前,将AutoCommit 设置为   
  187.                 // true   
  188.                 <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.closeConnection(conn);   
  189.                 conn = null;   
  190.             }   
  191.         } catch (Exception exx) {   
  192.             log.error(exx);   
  193.         }   
  194.     }   
  195.     public static void closeDBObject(Statement s, ResultSet r ,Connection conn,   
  196.             boolean autoCommitFlag) {   
  197.         // 关闭Statement   
  198.         try {   
  199.             if (s != null) {   
  200.                 s.close();   
  201.                 s = null;   
  202.             }   
  203.         } catch (Exception exx) {   
  204.             log.error(exx);   
  205.         }   
  206.         // 关闭ResultSet   
  207.         try {   
  208.             if (r != null) {   
  209.                 r.close();   
  210.                 r = null;   
  211.             }   
  212.         } catch (Exception exx) {   
  213.             log.error(exx);   
  214.         }          
  215.         // 关闭数据库链接   
  216.         try {   
  217.             if (conn != null) {   
  218.                 setAutoCommit(conn , true);// 无论传什么值,都应该在连接关闭前,将AutoCommit 设置为   
  219.                 // true   
  220.                 <SPAN class=hilite1><SPAN class=hilite1>Torque</SPAN></SPAN>.closeConnection(conn);   
  221.                 conn = null;   
  222.             }   
  223.         } catch (Exception exx) {   
  224.             log.error(exx);   
  225.         }   
  226.     }   
  227.   
  228.     public static void commit(Connection conn) {   
  229.         try {   
  230.             if (conn != null) {   
  231.                 if (conn.getMetaData().supportsTransactions()   
  232.                     && conn.getAutoCommit() == false)   
  233.                 {   
  234.                     conn.commit();   
  235.                     conn.setAutoCommit(true);   
  236.                 }   
  237.             }   
  238.         } catch (Exception exx) {   
  239.             log.error(exx);   
  240.         }   
  241.     }   
  242.   
  243.     public static void rollback(Connection conn) {   
  244.         try {   
  245.             if (conn != null) {   
  246.                 if (conn.getMetaData().supportsTransactions()   
  247.                     && conn.getAutoCommit() == false)   
  248.                 {   
  249.                     conn.rollback();   
  250.                     conn.setAutoCommit(true);   
  251.                 }   
  252.             }   
  253.         } catch (Exception ee) {   
  254.             log.error(ee);   
  255.         }   
  256.     }   
  257.     public static void setAutoCommit(Connection conn , boolean autoCommitFlag)   
  258.     {   
  259.         try  
  260.         {   
  261.             if (conn.getMetaData().supportsTransactions())   
  262.             {   
  263.                 conn.setAutoCommit(autoCommitFlag);   
  264.             }   
  265.         }   
  266.         catch (Exception e)   
  267.         {   
  268.             log.error(e);   
  269.         }      
  270.     }   
  271.   
  272.     public static List query(String querySql) {   
  273.         List results = null;   
  274.         try {   
  275.             results = BasePeer.executeQuery(querySql);   
  276.         } catch (Exception ee) {   
  277.             results = null;   
  278.             log.error(ee);   
  279.         }   
  280.         return results;   
  281.     }   
  282.     // singleRecord = true 表示只返回一条记录   
  283.     // singleRecord = false 表示返回所有记录   
  284.     public static List query(Connection conn, boolean singleRecord,   
  285.             String querySql) {   
  286.         List results = null;   
  287.         try {   
  288.             if (conn != null) {   
  289.                 results = BasePeer.executeQuery(querySql, singleRecord, conn);   
  290.             }   
  291.         } catch (Exception ee) {   
  292.             results = null;   
  293.             log.error(ee);   
  294.         }   
  295.         return results;   
  296.     }   
  297.     // singleRecord = true 表示只返回一条记录   
  298.     // singleRecord = false 表示返回所有记录   
  299.     public static List query(Connection conn,   
  300.             String querySql) {   
  301.         List results = null;   
  302.         boolean singleRecord = false;   
  303.         results = query(conn , singleRecord , querySql);   
  304.         return results;   
  305.     }   
  306.   
  307.     //查询数据库指定配置的数据库   
  308.     public static List query(String dbName ,String querySql) {   
  309.         List results = null;   
  310.         try {   
  311.             Connection conn = DBUtils.getDBConn(dbName);   
  312.             if(conn != null)   
  313.                 results = query(conn , querySql);   
  314.             else  
  315.                 results = null;   
  316.         } catch (Exception ee) {   
  317.             results = null;   
  318.             log.error(ee);   
  319.         }   
  320.         return results;   
  321.     }   
  322.   
  323.     public static int insertOrUpdate(String insertSql) {   
  324.         int results = -1;   
  325.         try {   
  326.             results = BasePeer.executeStatement(insertSql);   
  327.         } catch (Exception ee) {   
  328.             results = -1;              
  329.             log.error(ee);   
  330.         }   
  331.         return results;   
  332.     }   
  333.   
  334.     public static int insertOrUpdate(Connection conn, String insertSql) {   
  335.         int results = -1;   
  336.         try {   
  337.             if (conn != null) {   
  338.                 results = BasePeer.executeStatement(insertSql, conn);   
  339.             }   
  340.         } catch (Exception ee) {   
  341.             results = -1;   
  342.             log.error(ee);   
  343.         }   
  344.         return results;   
  345.     }   
  346.   
  347.        
  348.   
  349. }  
posted on 2008-05-22 11:33 rogerfan 阅读(1232) 评论(0)  编辑  收藏 所属分类: 【Torque学习】

只有注册用户登录后才能发表评论。


网站导航: