官方主页: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结尾):
- <?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
- <!DOCTYPE database SYSTEM
- "http://db.apache.org/torque/dtd/database_3_1.dtd">
- <database name="torquedb" defaultIdMethod="idbroker">
- <table name="book" description="Book Table">
- <column
- name="book_id"
- required="true"
- primaryKey="true"
- type="INTEGER"
- description="Book Id"/>
- <column
- name="title"
- required="true"
- type="VARCHAR"
- size="255"
- description="Book Title"/>
- <column
- name="isbn"
- required="true"
- type="VARCHAR"
- size="24"
- javaName="ISBN"
- description="ISBN Number"/>
- <column
- name="publisher_id"
- required="true"
- type="INTEGER"
- description="Foreign Key Publisher"/>
- <column
- name="author_id"
- required="true"
- type="INTEGER"
- description="Foreign Key Author"/>
- <foreign-key foreignTable="publisher" onDelete="cascade">
- <reference
- local="publisher_id"
- foreign="publisher_id"/>
- </foreign-key>
- <foreign-key foreignTable="author" onDelete="cascade">
- <reference
- local="author_id"
- foreign="author_id"/>
- </foreign-key>
- </table>
- <table name="publisher" description="Publisher Table">
- <column
- name="publisher_id"
- required="true"
- primaryKey="true"
- type="INTEGER"
- description="Publisher Id"/>
- <column
- name="name"
- required="true"
- type="VARCHAR"
- size="128"
- description="Publisher Name"/>
- </table>
- <table name="author" description="Author Table">
- <column
- name="author_id"
- required="true"
- primaryKey="true"
- type="INTEGER"
- description="Author Id"/>
- <column
- name="first_name"
- required="true"
- type="VARCHAR"
- size="128"
- description="First Name"/>
- <column
- name="last_name"
- required="true"
- type="VARCHAR"
- size="128"
- description="Last Name"/>
- </table>
- </database>
把torquedb-schema.xml放置到刚刚下载的Generator的解压文件夹/src/schema下,默认应该已经有一个id-table-schema.xml文件,这个文件是用来生成一个用以保存所有业务表的自增主键的数据表。
修改build.properties文件:
- # Licensed to the Apache Software Foundation (ASF) under one
- # or more contributor license agreements. See the NOTICE file
- # distributed with this work for additional information
- # regarding copyright ownership. The ASF licenses this file
- # to you under the Apache License, Version 2.0 (the
- # "License"); you may not use this file except in compliance
- # with the License. You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing,
- # software distributed under the License is distributed on an
- # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- # KIND, either express or implied. See the License for the
- # specific language governing permissions and limitations
- # under the License.
- # -------------------------------------------------------------------
- #
- # T O R Q U E C O N F I G U R A T I O N F I L E
- #
- # $Id: build.properties 591077 2007-11-01 16:42:56Z tv $
- #
- # -------------------------------------------------------------------
- # This file contains the most commonly used properties. For a
- # a complete list of build properties, please refer to:
- # http://db.apache.org/torque/releases/torque-3.3/generator/properties-reference.html
- # -------------------------------------------------------------------
- # -------------------------------------------------------------------
- #
- # P R O J E C T
- #
- # -------------------------------------------------------------------
- # This is the name of your Torque project. Your non-Java generated
- # files will be named using the project name selected below. If your
- # project=killerapp then you will have a generated:
- #
- # killerapp-schema.sql
- #
- # The custom is then to also rename your project XML schema from
- # project-schema.xml to killerapp-schema.xml. This is required
- # for a few targets such as datasql, datadump, and datadtd.
- # -------------------------------------------------------------------
- torque.project = torque_tutorial
- # -------------------------------------------------------------------
- #
- # T A R G E T D A T A B A S E
- #
- # -------------------------------------------------------------------
- # This is the target database, only considered when generating
- # the SQL for your Torque project. Your possible choices are:
- #
- # axion, cloudscape, db2, db2400, hypersonic, interbase, msaccess
- # mssql, mysql, oracle, postgresql, sapdb, sybase
- # -------------------------------------------------------------------
- torque.database = mysql
- # -------------------------------------------------------------------
- #
- # O B J E C T M O D E L I N F O R M A T I O N
- #
- # -------------------------------------------------------------------
- # These settings will allow you to customize the way your
- # Peer-based object model is created.
- # -------------------------------------------------------------------
- # addGetByNameMethod
- # If true, Torque adds methods to get database fields by name/position.
- #
- # addIntakeRetrievable
- # If true, the data objects will implement Intake's Retrievable
- # interface
- #
- # addSaveMethod
- # If true, Torque adds tracking code to determine how to save objects.
- #
- # addTimeStamp
- # If true, Torque true puts time stamps in generated om files.
- #
- # basePrefix
- # A string to pre-pend to the file names of base data and peer objects.
- #
- # complexObjectModel
- # If true, Torque generates data objects with collection support and
- # methods to easily retreive foreign key relationships.
- #
- # targetPackage
- # Sets the Java package the om files will generated to, e.g.
- # "com.company.project.om".
- #
- # useClasspath
- # If true, Torque will not look in the <code>templatePath</code> directory,
- # for templates, but instead load them from the classpath, allowing you to
- # use Torque without extracted it from the jar.
- #
- # useManagers
- # If true, Torque will generate Manager classes that use JCS for caching.
- # Still considered experimental.
- #
- # objectIsCaching
- # If true, Torque generates data objects that cache their foreign
- # key relationships. If this is not desired (because the underlying objects
- # can be manipulated from other code), set this property to false. This currently
- # cannot combined with the manager setting from above.
- #
- # silentDbFetch
- # If true, the getXXX() methods which retrieve associated objects
- # will fetch the associated objects silently. If false, only the
- # methods where a connection is specified explicitly will
- # fetch the associated objects silently; the methods where no connection
- # is specified will not do a silent fetch and return null if no previous
- # explicit fetch was made.
- # This setting has no effect if objectIsCaching is set to false.
- #
- #
- # generateBeans
- # If true, Torque will generate an additional bean for each data object,
- # plus methods to create beans from data objects and vice versa
- #
- # beanSuffix
- # A String to append to the class name of generated beans (if they are generated)
- #
- # enableJava5Features
- # If true, the generator will use Java5 generics in the generated code.
- # -------------------------------------------------------------------
- torquetorque.targetPackage = torque.generated
- torque.addGetByNameMethod = true
- torque.addIntakeRetrievable = false
- torque.addSaveMethod = true
- torque.addTimeStamp = true
- torque.basePrefix = Base
- torque.complexObjectModel = true
- torque.useClasspath = true
- torque.useManagers = false
- torque.objectIsCaching = true
- torque.silentDbFetch = true
- torque.generateBeans = false
- torque.beanSuffix = Bean
- torque.enableJava5Features = false
- # -------------------------------------------------------------------
- #
- # D A T A B A S E S E T T I N G S
- #
- # -------------------------------------------------------------------
- # JDBC connection settings. This is used by the JDBCToXML task that
- # will create an XML database schema from JDBC metadata. These
- # settings are also used by the SQL Ant task to initialize your
- # Torque system with the generated SQL.
- #
- # sameJavaName
- # If true, the JDBC task will set the javaName attribute for the tables
- # and columns to be the same as SQL name.
- # -------------------------------------------------------------------
- torque.targetPackage=examples.torque.peer
- torque.database.createUrl = jdbc:mysql://127.0.0.1:3306/mysql
- torque.database.buildUrl = jdbc:mysql://127.0.0.1:3306/torquedb
- torque.database.url = jdbc:mysql://127.0.0.1:3306/torquedb
- torque.database.driver = com.mysql.jdbc.Driver
- torque.database.user = root
- torque.database.password = root
- torque.database.host = 127.0.0.1
- 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晒出来:
- SET FOREIGN_KEY_CHECKS=0;
- -- ----------------------------
- -- Table structure for author
- -- ----------------------------
- CREATE TABLE `author` (
- `author_id` int(11) NOT NULL,
- `first_name` varchar(128) NOT NULL,
- `last_name` varchar(128) NOT NULL,
- PRIMARY KEY (`author_id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
- -- ----------------------------
- -- Table structure for book
- -- ----------------------------
- CREATE TABLE `book` (
- `book_id` int(11) NOT NULL,
- `title` varchar(255) NOT NULL,
- `isbn` varchar(24) NOT NULL,
- `publisher_id` int(11) NOT NULL,
- `author_id` int(11) NOT NULL,
- PRIMARY KEY (`book_id`),
- KEY `book_FK_1` (`publisher_id`),
- KEY `book_FK_2` (`author_id`),
- CONSTRAINT `book_FK_2` FOREIGN KEY (`author_id`) REFERENCES `author` (`author_id`) ON DELETE CASCADE,
- CONSTRAINT `book_FK_1` FOREIGN KEY (`publisher_id`) REFERENCES `publisher` (`publisher_id`) ON DELETE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
- -- ----------------------------
- -- Table structure for id_table
- -- ----------------------------
- CREATE TABLE `id_table` (
- `ID_TABLE_ID` int(11) NOT NULL,
- `TABLE_NAME` varchar(255) NOT NULL,
- `NEXT_ID` int(11) default NULL,
- `QUANTITY` int(11) default NULL,
- PRIMARY KEY (`ID_TABLE_ID`),
- UNIQUE KEY `TABLE_NAME` (`TABLE_NAME`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
- -- ----------------------------
- -- Table structure for publisher
- -- ----------------------------
- CREATE TABLE `publisher` (
- `publisher_id` int(11) NOT NULL,
- `name` varchar(128) NOT NULL,
- PRIMARY KEY (`publisher_id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
- -- ----------------------------
- -- Records
- -- ----------------------------
- INSERT INTO `id_table` VALUES ('1', 'author', '1', '1');
- INSERT INTO `id_table` VALUES ('2', 'book', '1', '1');
- INSERT INTO `id_table` VALUES ('3', 'publisher', '1', '1');
下载Torque运行包Runtime:http://db.apache.org/torque/download.html并解压,修改Torque.properties文件:
- # Licensed to the Apache Software Foundation (ASF) under one
- # or more contributor license agreements. See the NOTICE file
- # distributed with this work for additional information
- # regarding copyright ownership. The ASF licenses this file
- # to you under the Apache License, Version 2.0 (the
- # "License"); you may not use this file except in compliance
- # with the License. You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing,
- # software distributed under the License is distributed on an
- # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- # KIND, either express or implied. See the License for the
- # specific language governing permissions and limitations
- # under the License.
- 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 = ${torque.applicationRoot}/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
- # -------------------------------------------------------------------
- #
- # D E F A U L T S
- #
- # -------------------------------------------------------------------
- #
- # These values kick in, if you don't explicitly override them in your
- # various database settings. At the moment they're only used if you
- # configure the SharedPoolDataSourceFactory of the PerUserDataSourceFactory
- # as your data source provider. It does not work with JNDI.
- #
- # The example is shown for SharedPoolDataSource.
- #
- # -------------------------------------------------------------------
- # Time to wait for a connection to the database in milliseconds.
- torque.defaults.pool.maxWait = 10000
- # Maximum number of idle and active connections cached in a database
- # definition.
- # Note that, if you have multiple database definitions which access the
- # same database URL, they don't share the connections but you have
- # multiple pools and each has this maximum number. So if you have a
- # connection licensed database engine, you must multiply this number by
- # the number of times you use a specific database URL.
- torque.defaults.pool.maxIdle = 8
- torque.defaults.pool.maxActive = 10
- # How often the pool is checked for connection which stayed in the pool
- # for too long. Defaults to 5 minutes (5 * 60 * 1000)
- # remove property if the idle object evictor should not be run
- torque.defaults.pool.timeBetweenEvictionRunsMillis= 300000
- # Lifetime of an idle connection in the pool in milliseconds.
- # Defaults to one hour (1000 * 60 * 60)
- torque.defaults.pool.minEvictableIdleTimeMillis = 3600000
- # Sets the driver for the data sources.
- torque.defaults.connection.driver = com.mysql.jdbc.Driver
- # Sets the URL for the datasources
- torque.defaults.connection.url = jdbc:mysql://localhost:3306/torquedb
- # Sets login and password for the data sources.
- torque.defaults.connection.user = root
- torque.defaults.connection.password = root
- # -------------------------------------------------------------------
- #
- # 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=torquedb
- torque.database.torquedb.adapter=mysql
- # # Using commons-dbcp
- torque.dsfactory.torquedb.factory=org.apache.torque.dsfactory.SharedPoolDataSourceFactory
- # torque.dsfactory.bookstore.factory=org.apache.torque.dsfactory.PerUserPoolDataSourceFactory
- torque.dsfactory.torquedb.pool.maxIdle=8
- torque.dsfactory.torquedb.pool.maxActive=10
- torque.dsfactory.torquedb.pool.testOnBorrow=true
- torque.dsfactory.torquedb.pool.validationQuery=SELECT 1
- torque.dsfactory.torquedb.connection.driver = com.mysql.jdbc.Driver
- torque.dsfactory.torquedb.connection.url = jdbc:mysql://localhost:3306/torquedb
- torque.dsfactory.torquedb.connection.user = root
- torque.dsfactory.torquedb.connection.password = root
- # # Using jndi
- # torque.dsfactory.bookstore.factory=org.apache.torque.dsfactory.JndiDataSourceFactory
- # torque.dsfactory.bookstore.jndi.path=jdbc/bookstore
- # torque.dsfactory.bookstore.jndi.java.naming.factory.initial = org.apache.naming.java.javaURLContextFactory
- # torque.dsfactory.bookstore.jndi.java.naming.factory.url.pkgs = org.apache.naming
- # torque.dsfactory.bookstore.datasource.dataSourceName=jdbc/DBbookstore
- # torque.dsfactory.bookstore.datasource.jndiEnvironment.java.naming.factory.initial = org.apache.naming.java.javaURLContextFactory
- # torque.dsfactory.bookstore.datasource.jndiEnvironment.java.naming.factory.url.pkgs = org.apache.naming
- # torque.dsfactory.bookstore.datasource.maxIdle=8
- # torque.dsfactory.bookstore.datasource.maxActive=10
- # # ConnectionPoolDataSource
- # torque.dsfactory.bookstore.factory=org.apache.torque.dsfactory.JndiDataSourceFactory
- # torque.dsfactory.bookstore.jndi.path=jdbc/DBbookstore
- # torque.dsfactory.bookstore.jndi.java.naming.factory.initial = org.apache.naming.java.javaURLContextFactory
- # torque.dsfactory.bookstore.jndi.java.naming.factory.url.pkgs = org.apache.naming
- # torque.dsfactory.bookstore.datasource.classname=org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS
- # torque.dsfactory.bookstore.datasource.driver = org.gjt.mm.mysql.Driver
- # torque.dsfactory.bookstore.datasource.url = jdbc:mysql://localhost:3306/torque
- # torque.dsfactory.bookstore.datasource.user = user
- # torque.dsfactory.bookstore.datasource.password = password
- # 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=true
- # 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.default=torquedb后,下面的配置都要把属性中的bookstore改为torquedb。
这样可以把生成的PO以及配置文件组成工程,结构如下:
测试文件TestMain.java
- package examples.torque;
- import java.sql.Connection;
- import java.util.List;
- import org.apache.commons.configuration.PropertiesConfiguration;
- import org.apache.torque.Torque;
- import org.apache.torque.util.BasePeer;
- import org.apache.torque.util.Criteria;
- import org.apache.torque.util.Transaction;
- import com.workingdogs.village.Record;
- import examples.torque.peer.Author;
- import examples.torque.peer.AuthorPeer;
- import examples.torque.peer.Book;
- import examples.torque.peer.Publisher;
- public class TestMain {
- public static void main(String[] args) throws Exception {
- PropertiesConfiguration dbConfig = new PropertiesConfiguration();
- dbConfig.load("torque.properties");
- Torque.init(dbConfig);
- //Transaction
- Author author = new Author();
- author.setFirstName("shen");
- author.setLastName("bin");
- Publisher publisher = new Publisher();
- publisher.setName("publisherA");
- Book book = new Book();
- book.setTitle("titleA");
- book.setISBN("ISBNA");
- Connection conn = Transaction.begin(Torque.getDefaultDB());
- try {
- author.save(conn);//AuthorPeer.doInsert(author);
- publisher.save(conn);
- book.setPublisher(publisher);
- book.setAuthor(author);
- book.save(conn);
- } catch (Exception e) {
- Transaction.rollback(conn);
- } finally {
- Transaction.commit(conn);
- }
- //SQL Search
- List<?> list = BasePeer.executeQuery("select * from author");
- for (int i = 0; i < list.size(); i++) {
- Record record = (Record)list.get(i);
- System.out.println(record.getValue(3).asString());
- }
- //Criteria Search
- Criteria criteria = new Criteria();
- criteria.add(AuthorPeer.AUTHOR_ID, 1);
- list = AuthorPeer.doSelect(criteria);
- for (int i = 0; i < list.size(); i++) {
- System.out.println(list.get(i));
- }
- //Update
- author = (Author)list.get(0);
- author.setLastName("yan");
- author.save();
- }
- }
其他资料:
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