Introduction

Apache Torque is an object-relational mapper for java. In other words, Torque lets you access and manipulate data in a relational database using java objects. Unlike most other object-relational mappers, Torque does not use reflection to access user-provided classes, but it generates the necessary classes (including the Data Objects) from an XML schema describing the database layout. The XML file can either be written by hand or a starting point can be generated from an existing database. The XML schema can also be used to generate and execute a SQL script which creates all the tables in the database.

Apache Torque是一种object-relational mapper。Torque能让用户通过java object 访问或操作关系数据库中的数据。不同于大多数其他object-relational mappers,Torque访问用户提供的类不使用反射,而是使用由XML schema生成的必要的类(包括Data Objects)。

Torque has two primary foci: It is a tool for java code generation and, building on top of that, it provides object-relational mapping (ORM) for database access in java. These two aspects are treated in different parts of this tutorial; the two parts can be read independently of each other.

Torque有两个用途:一个是作为java code生成的工具;另一个是基于生成的代码,提供object-relational mapping (ORM) 访问数据库。这两个方面可以认为是不同的部分,独立对待。ORM部分包含创建数据库和读写数据。code生成部分表示如何使用Torque generator生成自定义code (O/R classes)。

OR-Mapping

The Torque ORM Tutorial consists of the following steps:

步骤一:配置Torque generation process

使用Maven或者Ant配置的依赖和plugin。依赖主要有Torque runtime或者db driver (比如mysql-connector-java)。plugin主要是一些根据模版生产代码的配置

步骤二:定义数据库schema

第二个需要编辑的配置文件是database schema。Torque里面database schema是一个描述数据库结构的XML file。文件可以定义某个数据库的表,column名字和类型,表的键和索引。

步骤三:调用Torque generator

完成了maven/ant配置和database schema定义后,接下来可以生产object model和创建数据库表。object model的创建会生成代表数据库结构的java源文件。通过这些类我们可以操作数据库中的数据。此外,Torque还会生成SQL去创建数据库表。

Torque创建object model时,会为每个table生成8各类: 4个有Base前缀的和4个没有前缀的。有Base前缀的类不可修改(因为每次生成都会被覆盖掉),没有前缀的类是Base前缀类的子类,可以覆盖父类的实现。

Note: Torque会假设数据库已经存在,在执行Sql的时候,首先会drop掉相应数据。

步骤四:配置Torque runtime

配置Torque运行环境简单来讲,就是配置运行时的连接信息,比如adapter,driver,url, 用户名和密码。

Property Description
torque.database.default Torque has the ability to use multiple databases. This property specifies which database is to be used as the default.
torque.database.XXX.adapter Torque has the ability to deal with multiple database systems. This property specifies the database adapter to use.
torque.dsfactory.XXX.factory The factory class that will be used to provide database connections.
torque.dsfactory.XXX.connection.driver The JDBC database driver to use when connecting to your database.
torque.database.XXX.connection.url The URL that will be used to access your database. Torque's generated object model will perform all database operations using this URL. This value should reflect the database name specified in your database schema file (see the database element's name attribute).
torque.database.XXX.connection.user The username that has sufficient privileges to access your database. This user does not require privileges to create and drop tables, unlike the user that was specified in project.properties.
torque.database.XXX.connection.password The password for the specified username.

一个简单的例子:

torque.database.default = bookstore
torque.database.bookstore.adapter = mysql torque.dsfactory.bookstore.factory = org.apache.torque.dsfactory.SharedPoolDataSourceFactory
torque.dsfactory.bookstore.connection.driver = org.gjt.mm.mysql.Driver
torque.dsfactory.bookstore.connection.url = jdbc:mysql://localhost:3306/bookstore
torque.dsfactory.bookstore.connection.user = root
torque.dsfactory.bookstore.connection.password = password

步骤五: 把Torque用起来

生成完必要的class,数据库表,以及配置好了运行的连接信息。接下来就是如何用在应用程序中。

package org.apache.torque.tutorial.om;

import java.io.InputStream;
import java.util.List; import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.torque.Torque;
import org.apache.torque.criteria.Criteria; public class Bookstore
{
public static void main(String[] args)
{
try
{
// Initializing Logging
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.WARN); // Initializing Torque
InputStream torqueConfigStream
= Bookstore.class.getResourceAsStream("/torque.properties");
PropertiesConfiguration torqueConfiguration
= new PropertiesConfiguration();
torqueConfiguration.load(torqueConfigStream);
Torque.init(torqueConfiguration); /*
* Creating new objects. These will be inserted into your database
* automatically when the save method is called.
*/
Publisher addison = new Publisher();
addison.setName("Addison Wesley Professional");
addison.save(); Author bloch = new Author();
bloch.setFirstName("Joshua");
bloch.setLastName("Bloch");
bloch.save(); /*
* An alternative method to inserting rows in your database.
*/
Author stevens = new Author();
stevens.setFirstName("W.");
stevens.setLastName("Stevens");
AuthorPeer.doInsert(stevens); /*
* Using the convenience methods to handle the foreign keys.
*/
Book effective = new Book();
effective.setTitle("Effective Java");
effective.setISBN("0-618-12902-2");
effective.setPublisher(addison);
effective.setAuthor(bloch);
effective.save(); /*
* Inserting the foreign-keys manually.
*/
Book tcpip = new Book();
tcpip.setTitle("TCP/IP Illustrated, Volume 1");
tcpip.setISBN("0-201-63346-9");
tcpip.setPublisherId(addison.getPublisherId());
tcpip.setAuthorId(stevens.getAuthorId());
tcpip.save(); /*
* Selecting all books from the database and printing the results to
* stdout using our helper method defined in BookPeer (doSelectAll).
*/
System.out.println("Full booklist:\n");
List<Book> booklist = BookPeer.doSelectAll();
printBooklist(booklist); /*
* Selecting specific objects. Just search for objects that match
* this criteria (and print to stdout).
*/
System.out.println("Booklist (specific ISBN):\n");
Criteria crit = new Criteria();
crit.where(BookPeer.ISBN, "0-201-63346-9");
booklist = BookPeer.doSelect(crit);
printBooklist(booklist); /*
* Updating data. These lines will swap the authors of the two
* books. The booklist is printed to stdout to verify the results.
*/
effective.setAuthor(stevens);
effective.save(); tcpip.setAuthor(bloch);
BookPeer.doUpdate(tcpip); System.out.println("Booklist (authors swapped):\n");
booklist = BookPeer.doSelectAll();
printBooklist(booklist); /*
* Deleting data. These lines will delete the data that matches the
* specified criteria.
*/
crit = new Criteria();
crit.where(BookPeer.ISBN, "0-618-12902-2");
BookPeer.doDelete(crit); crit = new Criteria();
crit.where(BookPeer.ISBN, "0-201-63346-9");
crit.and(BookPeer.TITLE, "TCP/IP Illustrated, Volume 1");
BookPeer.doDelete(crit); /*
* Deleting data by passing Data Objects instead of specifying
* criteria.
*/
AuthorPeer.doDelete(bloch);
AuthorPeer.doDelete(stevens);
PublisherPeer.doDelete(addison); System.out.println("Booklist (should be empty):\n");
booklist = BookPeer.doSelectAll();
printBooklist(booklist);
}
catch (Exception e)
{
e.printStackTrace();
}
} /*
* Helper method to print a booklist to standard out.
*/
private static void printBooklist(List<Book> booklist)
{
for (Book book : booklist)
{
System.out.println(book);
}
}
}

Reference

Torque tutorial:https://db.apache.org/torque/torque-4.0/documentation/tutorial/orm/index.html

Apache Torque入门学习的更多相关文章

  1. Apache Pig入门学习文档(一)

    1,Pig的安装    (一)软件要求    (二)下载Pig      (三)编译Pig 2,运行Pig    (一)Pig的所有执行模式    (二)pig的交互式模式    (三)使用pig脚本 ...

  2. Apache Torque的使用

    这篇文章学习如何使用Torque,作为一个ORM(a tool that maps relational databases to java classes) 用Torque访问数据库,需要如下步骤 ...

  3. Hadoop入门学习笔记---part2

    在<Hadoop入门学习笔记---part1>中感觉自己虽然总结的比较详细,但是始终感觉有点凌乱.不够系统化,不够简洁.经过自己的推敲和总结,现在在此处概括性的总结一下,认为在准备搭建ha ...

  4. MyBatis入门学习教程-使用MyBatis对表执行CRUD操作

    上一篇MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对use ...

  5. MyBatis入门学习(二)

    在MyBatis入门学习(一)中我们完成了对MyBatis简要的介绍以及简单的入门小项目测试,主要完成对一个用户信息的查询.这一节我们主要来简要的介绍MyBatis框架的增删改查操作,加深对该框架的了 ...

  6. Hadoop入门学习笔记---part1

    随着毕业设计的进行,大学四年正式进入尾声.任你玩四年的大学的最后一次作业最后在激烈的选题中尘埃落定.无论选择了怎样的选题,无论最后的结果是怎样的,对于大学里面的这最后一份作业,也希望自己能够尽心尽力, ...

  7. Lucene.net入门学习

    Lucene.net入门学习(结合盘古分词)   Lucene简介 Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,即它不是一个完整的全 ...

  8. JAVAEE——BOS物流项目07:WebService入门、apache CXF入门、基于CXF发布CRM服务

    1 学习计划 1.WebService入门 n 什么是WebService n 调用网络上的WebService服务 n SOAP和WSDL概念 n 基于JDK1.7发布一个简单的WebService ...

  9. Hive入门学习--HIve简介

    现在想要应聘大数据分析或者数据挖掘岗位,很多都需要会使用Hive,Mapreduce,Hadoop等这些大数据分析技术.为了充实自己就先从简单的Hive开始吧.接下来的几篇文章是记录我如何入门学习Hi ...

随机推荐

  1. ERROR 2003 (HY000): Can't connect to MySQL server on 'ip address' (111)的处理办法

    远程连接mysql数据库时可以使用以下指令 mysql -h 192.168.1.104 -u root -p 如果是初次安装mysql,需要将所有/etc/mysql/内的所有配置文件的bind-a ...

  2. 2.lvm动态逻辑卷

    Lvm动态逻辑卷 一.             基本概念 LVM 把实际的物理磁盘数据映射到一个简单而灵活的虚拟逻辑存储视图上,藉以控制磁盘资源: 也就是重新考虑了管理文件系统和卷的方法,在文件系统管 ...

  3. 基于英特尔® 至强™ 处理器 E5 产品家族的多节点分布式内存系统上的 Caffe* 培训

    原文链接 深度神经网络 (DNN) 培训属于计算密集型项目,需要在现代计算平台上花费数日或数周的时间方可完成. 在最近的一篇文章<基于英特尔® 至强™ E5 产品家族的单节点 Caffe 评分和 ...

  4. 项目游戏开发日记 No.0x000005

    14软二杨近星(2014551622) 还有一周就要交项目了, 看着周围的人也都忙碌了起来, 看着大部分人的项目都已经初具容貌, 我们团队里面也搞得人心惶惶, 一来是, 时间不多了, 还有很多事情要做 ...

  5. [bzoj1007][HNOI2008][水平可见直线] (斜率不等式)

    Description 在xoy直角坐标平面上有n条直线L1,L2,...Ln,若在y值为正无穷大处往下看,能见到Li的某个子线段,则称Li为 可见的,否则Li为被覆盖的. 例如,对于直线: L1:y ...

  6. docker学习(8) 在mac机上搭建私有仓库

    docker的私有仓库类似maven的私服,一般用于公司内部搭建一个类似docker hub的环境,这样上传.下载镜像速度较快,本文将演示如何在mac上利用docker-machine搭建无需SSL证 ...

  7. [LeetCode] Add Digits 加数字

    Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. ...

  8. [LeetCode] Merge Two Sorted Lists 混合插入有序链表

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing t ...

  9. 如何在Microsoft Edge浏览器中添加一个Hello World插件

    注:本文提到的代码示例下载地址> How to add a Hello World extension to Microsoft Edge Microsoft Edge 随着Win 10一起推出 ...

  10. solr.net的使用

    引子 最近在做一个日志系统,用普通关系型数据库做数据查询遇到了查询的瓶颈,想到了用成熟的搜索应用服务,我所知道的比较成熟的搜索应用服务有solr和es(elasticsearch),由于时间比较仓促, ...