Torque:Apache又一O/R Mapping框架

来源:互联网 发布:淘宝漏洞免费买东西 编辑:程序博客网 时间:2024/05/16 14:01

官方主页:http://db.apache.org/torque/index.html

本文是在阅读http://www.blogjava.net/fanyingjie/archive/2008/05/22/202109.html的基础上进行的一些补充。

使用的版本是:3.3。

 

这个O/R Mapping框架虽然不像Hibernate那样实现强大,但在很多方面都体现出他的易用性。

步骤如下:

首先:使用Torque的Generator生成PO和数据表。假设想要新建的数据库名为torquedb.

下载Generator:http://db.apache.org/torque/download.html,并解压。

定义torquedb-schema.xml文件如下(注意:貌似必须以-schema.xml结尾):

  1. <?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
  2. <!DOCTYPE database SYSTEM
  3.  "http://db.apache.org/torque/dtd/database_3_1.dtd">
  4. <database name="torquedb" defaultIdMethod="idbroker">
  5.  <table name="book" description="Book Table">
  6.     <column
  7.       name="book_id"
  8.       required="true"
  9.       primaryKey="true"
  10.       type="INTEGER"
  11.       description="Book Id"/>
  12.     <column
  13.       name="title"
  14.       required="true"
  15.       type="VARCHAR"
  16.       size="255"
  17.       description="Book Title"/>
  18.     <column
  19.       name="isbn"
  20.       required="true"
  21.       type="VARCHAR"
  22.       size="24"
  23.       javaName="ISBN"
  24.       description="ISBN Number"/>
  25.     <column
  26.       name="publisher_id"
  27.       required="true"
  28.       type="INTEGER"
  29.       description="Foreign Key Publisher"/>
  30.     <column
  31.       name="author_id"
  32.       required="true"
  33.       type="INTEGER"
  34.       description="Foreign Key Author"/>
  35.     <foreign-key foreignTable="publisher" onDelete="cascade">
  36.       <reference
  37.         local="publisher_id"
  38.         foreign="publisher_id"/>
  39.     </foreign-key>
  40.     <foreign-key foreignTable="author" onDelete="cascade">
  41.       <reference
  42.         local="author_id"
  43.         foreign="author_id"/>
  44.     </foreign-key>
  45.  </table>
  46.  <table name="publisher" description="Publisher Table">
  47.     <column
  48.       name="publisher_id"
  49.       required="true"
  50.       primaryKey="true"
  51.       type="INTEGER"
  52.       description="Publisher Id"/>
  53.     <column
  54.       name="name"
  55.       required="true"
  56.       type="VARCHAR"
  57.       size="128"
  58.      description="Publisher Name"/>
  59.  </table>
  60.  <table name="author" description="Author Table">
  61.     <column
  62.       name="author_id"
  63.       required="true"
  64.       primaryKey="true"
  65.       type="INTEGER"
  66.       description="Author Id"/>
  67.     <column
  68.       name="first_name"
  69.       required="true"
  70.       type="VARCHAR"
  71.       size="128"
  72.       description="First Name"/>
  73.     <column
  74.       name="last_name"
  75.       required="true"
  76.       type="VARCHAR"
  77.       size="128"
  78.       description="Last Name"/>
  79.  </table>
  80. </database>

把torquedb-schema.xml放置到刚刚下载的Generator的解压文件夹/src/schema下,默认应该已经有一个id-table-schema.xml文件,这个文件是用来生成一个用以保存所有业务表的自增主键的数据表。

修改build.properties文件:

  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements.  See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership.  The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License.  You may obtain a copy of the License at
  8. #
  9. #   http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied.  See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. # -------------------------------------------------------------------
  18. #
  19. # T O R Q U E  C O N F I G U R A T I O N  F I L E
  20. #
  21. # $Id: build.properties 591077 2007-11-01 16:42:56Z tv $
  22. #
  23. # -------------------------------------------------------------------
  24. # This file contains the most commonly used properties. For a
  25. # a complete list of build properties, please refer to:
  26. #   http://db.apache.org/torque/releases/torque-3.3/generator/properties-reference.html
  27. # -------------------------------------------------------------------
  28. # -------------------------------------------------------------------
  29. #
  30. #  P R O J E C T
  31. #
  32. # -------------------------------------------------------------------
  33. # This is the name of your Torque project. Your non-Java generated
  34. # files will be named using the project name selected below. If your
  35. project=killerapp then you will have a generated:
  36. #
  37. #   killerapp-schema.sql
  38. #
  39. # The custom is then to also rename your project XML schema from
  40. # project-schema.xml to killerapp-schema.xml. This is required
  41. # for a few targets such as datasql, datadump, and datadtd.
  42. # -------------------------------------------------------------------
  43. torque.project = torque_tutorial
  44. # -------------------------------------------------------------------
  45. #
  46. #  T A R G E T  D A T A B A S E
  47. #
  48. # -------------------------------------------------------------------
  49. # This is the target database, only considered when generating
  50. # the SQL for your Torque project. Your possible choices are:
  51. #
  52. #   axion, cloudscape, db2, db2400, hypersonic, interbase, msaccess
  53. #   mssql, mysql, oracle, postgresql, sapdb, sybase
  54. # -------------------------------------------------------------------
  55. torque.database = mysql
  56. # -------------------------------------------------------------------
  57. #
  58. #  O B J E C T  M O D E L  I N F O R M A T I O N
  59. #
  60. # -------------------------------------------------------------------
  61. # These settings will allow you to customize the way your
  62. # Peer-based object model is created.
  63. # -------------------------------------------------------------------
  64. # addGetByNameMethod
  65. #   If true, Torque adds methods to get database fields by name/position.
  66. #
  67. # addIntakeRetrievable
  68. #   If true, the data objects will implement Intake's Retrievable
  69. #   interface
  70. #
  71. # addSaveMethod
  72. #   If true, Torque adds tracking code to determine how to save objects.
  73. #
  74. # addTimeStamp
  75. #   If true, Torque true puts time stamps in generated om files.
  76. #
  77. # basePrefix
  78. #   A string to pre-pend to the file names of base data and peer objects.
  79. #
  80. # complexObjectModel
  81. #   If true, Torque generates data objects with collection support and
  82. #   methods to easily retreive foreign key relationships.
  83. #
  84. # targetPackage
  85. #   Sets the Java package the om files will generated to, e.g.
  86. #   "com.company.project.om".
  87. #
  88. # useClasspath
  89. #   If true, Torque will not look in the <code>templatePath</code> directory,
  90. #   for templates, but instead load them from the classpath, allowing you to
  91. #   use Torque without extracted it from the jar.
  92. #
  93. # useManagers
  94. #   If true, Torque will generate Manager classes that use JCS for caching.
  95. #   Still considered experimental.
  96. #
  97. # objectIsCaching
  98. #   If true, Torque generates data objects that cache their foreign
  99. #   key relationships. If this is not desired (because the underlying objects
  100. #   can be manipulated from other code), set this property to false. This currently
  101. #   cannot combined with the manager setting from above.
  102. #
  103. # silentDbFetch
  104. #   If true, the getXXX() methods which retrieve associated objects
  105. #   will fetch the associated objects silently. If false, only the
  106. #   methods where a connection is specified explicitly will
  107. #   fetch the associated objects silently; the methods where no connection
  108. #   is specified will not do a silent fetch and return null if no previous
  109. #   explicit fetch was made.
  110. #   This setting has no effect if objectIsCaching is set to false.
  111. #
  112. #
  113. # generateBeans
  114. #   If true, Torque will generate an additional bean for each data object,
  115. #   plus methods to create beans from data objects and vice versa
  116. #
  117. # beanSuffix
  118. #   A String to append to the class name of generated beans (if they are generated)
  119. #
  120. # enableJava5Features
  121. #   If true, the generator will use Java5 generics in the generated code.
  122. # -------------------------------------------------------------------
  123. torquetorque.targetPackage = torque.generated
  124. torque.addGetByNameMethod = true
  125. torque.addIntakeRetrievable = false
  126. torque.addSaveMethod = true
  127. torque.addTimeStamp = true
  128. torque.basePrefix = Base
  129. torque.complexObjectModel = true
  130. torque.useClasspath = true
  131. torque.useManagers = false
  132. torque.objectIsCaching = true
  133. torque.silentDbFetch = true
  134. torque.generateBeans = false
  135. torque.beanSuffix = Bean
  136. torque.enableJava5Features = false
  137. # -------------------------------------------------------------------
  138. #
  139. #  D A T A B A S E  S E T T I N G S
  140. #
  141. # -------------------------------------------------------------------
  142. # JDBC connection settings. This is used by the JDBCToXML task that
  143. # will create an XML database schema from JDBC metadata. These
  144. # settings are also used by the SQL Ant task to initialize your
  145. # Torque system with the generated SQL.
  146. #
  147. # sameJavaName
  148. #   If true, the JDBC task will set the javaName attribute for the tables
  149. #   and columns to be the same as SQL name.
  150. # -------------------------------------------------------------------
  151. torque.targetPackage=examples.torque.peer
  152. torque.database.createUrl = jdbc:mysql://127.0.0.1:3306/mysql
  153. torque.database.buildUrl = jdbc:mysql://127.0.0.1:3306/torquedb
  154. torque.database.url = jdbc:mysql://127.0.0.1:3306/torquedb
  155. torque.database.driver = com.mysql.jdbc.Driver
  156. torque.database.user = root
  157. torque.database.password = root
  158. torque.database.host = 127.0.0.1
  159. torque.sameJavaName = false

注意上面粗体部分的修改内容。

运行Ant,命令如下(参考:http://db.apache.org/torque/releases/torque-3.3/generator/index.html):

ant -f build-torque.xml

此时在刚刚下载的Generator的解压文件夹/src/java下生成了工程需要PO,pachkage由上述配置文件torque.targetPackage所指定。

 

资料上说运行ant -f build-torque.xml create-db可新建数据库,我没有成功,这里把DDL晒出来:

  1. SET FOREIGN_KEY_CHECKS=0;
  2. -- ----------------------------
  3. -- Table structure for author
  4. -- ----------------------------
  5. CREATE TABLE `author` (
  6.   `author_id` int(11) NOT NULL,
  7.   `first_name` varchar(128) NOT NULL,
  8.   `last_name` varchar(128) NOT NULL,
  9.   PRIMARY KEY  (`author_id`)
  10. ENGINE=InnoDB DEFAULT CHARSET=latin1;
  11. -- ----------------------------
  12. -- Table structure for book
  13. -- ----------------------------
  14. CREATE TABLE `book` (
  15.   `book_id` int(11) NOT NULL,
  16.   `title` varchar(255) NOT NULL,
  17.   `isbn` varchar(24) NOT NULL,
  18.   `publisher_id` int(11) NOT NULL,
  19.   `author_id` int(11) NOT NULL,
  20.   PRIMARY KEY  (`book_id`),
  21.   KEY `book_FK_1` (`publisher_id`),
  22.   KEY `book_FK_2` (`author_id`),
  23.   CONSTRAINT `book_FK_2` FOREIGN KEY (`author_id`) REFERENCES `author` (`author_id`) ON DELETE CASCADE,
  24.   CONSTRAINT `book_FK_1` FOREIGN KEY (`publisher_id`) REFERENCES `publisher` (`publisher_id`) ON DELETE CASCADE
  25. ENGINE=InnoDB DEFAULT CHARSET=latin1;
  26. -- ----------------------------
  27. -- Table structure for id_table
  28. -- ----------------------------
  29. CREATE TABLE `id_table` (
  30.   `ID_TABLE_ID` int(11) NOT NULL,
  31.   `TABLE_NAME` varchar(255) NOT NULL,
  32.   `NEXT_ID` int(11) default NULL,
  33.   `QUANTITY` int(11) default NULL,
  34.   PRIMARY KEY  (`ID_TABLE_ID`),
  35.   UNIQUE KEY `TABLE_NAME` (`TABLE_NAME`)
  36. ENGINE=InnoDB DEFAULT CHARSET=latin1;
  37. -- ----------------------------
  38. -- Table structure for publisher
  39. -- ----------------------------
  40. CREATE TABLE `publisher` (
  41.   `publisher_id` int(11) NOT NULL,
  42.   `name` varchar(128) NOT NULL,
  43.   PRIMARY KEY  (`publisher_id`)
  44. ENGINE=InnoDB DEFAULT CHARSET=latin1;
  45. -- ----------------------------
  46. -- Records 
  47. -- ----------------------------
  48. INSERT INTO `id_table` VALUES ('1', 'author', '1', '1');
  49. INSERT INTO `id_table` VALUES ('2', 'book', '1', '1');
  50. INSERT INTO `id_table` VALUES ('3', 'publisher', '1', '1');

下载Torque运行包Runtime:http://db.apache.org/torque/download.html并解压,修改Torque.properties文件:

  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements.  See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership.  The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License.  You may obtain a copy of the License at
  8. #
  9. #   http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied.  See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. torque.applicationRoot = .
  18. # -------------------------------------------------------------------
  19. #
  20. #  L O G G I N G
  21. #
  22. # -------------------------------------------------------------------
  23. # We use Log4J for all Torque logging and we embed the log4j
  24. # properties within our application configuration.
  25. # -------------------------------------------------------------------
  26. # This first category is required and the category
  27. # must be named 'default'. This is used for all logging
  28. # where an explicit category is not specified.
  29. log4j.category.org.apache.torque = ALL, org.apache.torque
  30. log4j.appender.org.apache.torque = org.apache.log4j.FileAppender
  31. log4j.appender.org.apache.torque.file = ${torque.applicationRoot}/logs/torque.log
  32. log4j.appender.org.apache.torque.layout = org.apache.log4j.PatternLayout
  33. log4j.appender.org.apache.torque.layout.conversionPattern = %d [%t] %-5p %c - %m%n
  34. log4j.appender.org.apache.torque.append = false
  35. # -------------------------------------------------------------------
  36. #
  37. #  D E F A U L T S
  38. #
  39. # -------------------------------------------------------------------
  40. #
  41. # These values kick in, if you don't explicitly override them in your
  42. # various database settings. At the moment they're only used if you
  43. # configure the SharedPoolDataSourceFactory of the PerUserDataSourceFactory
  44. # as your data source provider. It does not work with JNDI.
  45. #
  46. # The example is shown for SharedPoolDataSource.
  47. #
  48. # -------------------------------------------------------------------
  49. # Time to wait for a connection to the database in milliseconds.
  50. torque.defaults.pool.maxWait = 10000
  51. # Maximum number of idle and active connections cached in a database
  52. # definition.
  53. # Note that, if you have multiple database definitions which access the
  54. # same database URL, they don't share the connections but you have
  55. # multiple pools and each has this maximum number. So if you have a
  56. # connection licensed database engine, you must multiply this number by
  57. # the number of times you use a specific database URL.
  58. torque.defaults.pool.maxIdle = 8
  59. torque.defaults.pool.maxActive = 10
  60. # How often the pool is checked for connection which stayed in the pool
  61. # for too long. Defaults to 5 minutes (5 * 60 * 1000)
  62. # remove property if the idle object evictor should not be run
  63. torque.defaults.pool.timeBetweenEvictionRunsMillis300000
  64. # Lifetime of an idle connection in the pool in milliseconds.
  65. # Defaults to one hour (1000 * 60 * 60)
  66. torque.defaults.pool.minEvictableIdleTimeMillis = 3600000
  67. # Sets the driver for the data sources.
  68. torque.defaults.connection.driver = com.mysql.jdbc.Driver
  69. # Sets the URL for the datasources
  70. torque.defaults.connection.url = jdbc:mysql://localhost:3306/torquedb
  71. # Sets login and password for the data sources.
  72. torque.defaults.connection.user = root
  73. torque.defaults.connection.password = root
  74. # -------------------------------------------------------------------
  75. #
  76. #  T O R Q U E  P R O P E R T I E S
  77. #
  78. # -------------------------------------------------------------------
  79. # These are your database settings. Look in the
  80. # org.apache.torque.pool.* packages for more information.
  81. #
  82. # The parameters to connect to the default database.  You MUST
  83. # configure these properly.
  84. # -------------------------------------------------------------------
  85. torque.database.default=torquedb
  86. torque.database.torquedb.adapter=mysql
  87. # # Using commons-dbcp
  88. torque.dsfactory.torquedb.factory=org.apache.torque.dsfactory.SharedPoolDataSourceFactory
  89. torque.dsfactory.bookstore.factory=org.apache.torque.dsfactory.PerUserPoolDataSourceFactory
  90. torque.dsfactory.torquedb.pool.maxIdle=8
  91. torque.dsfactory.torquedb.pool.maxActive=10
  92. torque.dsfactory.torquedb.pool.testOnBorrow=true
  93. torque.dsfactory.torquedb.pool.validationQuery=SELECT 1
  94. torque.dsfactory.torquedb.connection.driver = com.mysql.jdbc.Driver
  95. torque.dsfactory.torquedb.connection.url = jdbc:mysql://localhost:3306/torquedb
  96. torque.dsfactory.torquedb.connection.user = root
  97. torque.dsfactory.torquedb.connection.password = root
  98. # # Using jndi
  99. torque.dsfactory.bookstore.factory=org.apache.torque.dsfactory.JndiDataSourceFactory
  100. torque.dsfactory.bookstore.jndi.path=jdbc/bookstore
  101. torque.dsfactory.bookstore.jndi.java.naming.factory.initial = org.apache.naming.java.javaURLContextFactory
  102. torque.dsfactory.bookstore.jndi.java.naming.factory.url.pkgs = org.apache.naming
  103. torque.dsfactory.bookstore.datasource.dataSourceName=jdbc/DBbookstore
  104. torque.dsfactory.bookstore.datasource.jndiEnvironment.java.naming.factory.initial = org.apache.naming.java.javaURLContextFactory
  105. torque.dsfactory.bookstore.datasource.jndiEnvironment.java.naming.factory.url.pkgs = org.apache.naming
  106. torque.dsfactory.bookstore.datasource.maxIdle=8
  107. torque.dsfactory.bookstore.datasource.maxActive=10
  108. # # ConnectionPoolDataSource
  109. torque.dsfactory.bookstore.factory=org.apache.torque.dsfactory.JndiDataSourceFactory
  110. torque.dsfactory.bookstore.jndi.path=jdbc/DBbookstore
  111. torque.dsfactory.bookstore.jndi.java.naming.factory.initial = org.apache.naming.java.javaURLContextFactory
  112. torque.dsfactory.bookstore.jndi.java.naming.factory.url.pkgs = org.apache.naming
  113. torque.dsfactory.bookstore.datasource.classname=org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS
  114. torque.dsfactory.bookstore.datasource.driver = org.gjt.mm.mysql.Driver
  115. torque.dsfactory.bookstore.datasource.url = jdbc:mysql://localhost:3306/torque
  116. torque.dsfactory.bookstore.datasource.user = user
  117. torque.dsfactory.bookstore.datasource.password = password
  118. # Determines if the quantity column of the IDBroker's id_table should
  119. # be increased automatically if requests for ids reaches a high
  120. # volume.
  121. torque.idbroker.clever.quantity=true
  122. # Determines whether the managers cache instances of the business objects.
  123. # And also whether the MethodResultCache will really cache results.
  124. torque.manager.useCache = true

注意:设置torque.database.default=torquedb后,下面的配置都要把属性中的bookstore改为torquedb

 

这样可以把生成的PO以及配置文件组成工程,结构如下:

 

测试文件TestMain.java

  1. package examples.torque;
  2. import java.sql.Connection;
  3. import java.util.List;
  4. import org.apache.commons.configuration.PropertiesConfiguration;
  5. import org.apache.torque.Torque;
  6. import org.apache.torque.util.BasePeer;
  7. import org.apache.torque.util.Criteria;
  8. import org.apache.torque.util.Transaction;
  9. import com.workingdogs.village.Record;
  10. import examples.torque.peer.Author;
  11. import examples.torque.peer.AuthorPeer;
  12. import examples.torque.peer.Book;
  13. import examples.torque.peer.Publisher;
  14. public class TestMain {
  15.     public static void main(String[] args) throws Exception {
  16.         
  17.         PropertiesConfiguration dbConfig = new PropertiesConfiguration();
  18.         dbConfig.load("torque.properties");
  19.         Torque.init(dbConfig);
  20.         
  21.         //Transaction
  22.         Author author = new Author();
  23.         author.setFirstName("shen");
  24.         author.setLastName("bin");
  25.         Publisher publisher = new Publisher();
  26.         publisher.setName("publisherA");
  27.         Book book = new Book();
  28.         book.setTitle("titleA");
  29.         book.setISBN("ISBNA");
  30.         Connection conn = Transaction.begin(Torque.getDefaultDB());
  31.         try {
  32.             author.save(conn);//AuthorPeer.doInsert(author);
  33.             publisher.save(conn);
  34.             book.setPublisher(publisher);
  35.             book.setAuthor(author);
  36.             book.save(conn);
  37.         } catch (Exception e) {
  38.             Transaction.rollback(conn);
  39.         } finally {
  40.             Transaction.commit(conn);
  41.         }
  42.         
  43.         //SQL Search
  44.         List<?> list = BasePeer.executeQuery("select * from author");
  45.         for (int i = 0; i < list.size(); i++) {
  46.             Record record = (Record)list.get(i);
  47.             System.out.println(record.getValue(3).asString());
  48.         }
  49.         
  50.         //Criteria Search
  51.         Criteria criteria = new Criteria();
  52.         criteria.add(AuthorPeer.AUTHOR_ID, 1);
  53.         list = AuthorPeer.doSelect(criteria);
  54.         for (int i = 0; i < list.size(); i++) {
  55.             System.out.println(list.get(i));
  56.         }
  57.         
  58.         //Update
  59.         author = (Author)list.get(0);
  60.         author.setLastName("yan");
  61.         author.save();
  62.     }
  63. }

其他资料:

http://blog.csdn.net/keepeye/archive/2005/05/26/381681.aspx

http://betterman-zeng.blogbus.com/logs/6360701.html

Criteria用法:

http://db.apache.org/torque/releases/torque-3.3/runtime/reference/read-from-db.html