Introduction to ActiveJDBC – ActiveJDBC简介

最后修改: 2018年 2月 17日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

ActiveJDBC is a lightweight ORM following the core ideas of ActiveRecord, the primary ORM of Ruby on Rails.

ActiveJDBC是一个轻量级的ORM,遵循ActiveRecord的核心思想,是Ruby on Rails的主要ORM。

It focuses on simplifying the interaction with databases by removing the extra layer of typical persistence managers and focuses on the usage of SQL rather than creating a new query language.

它侧重于通过去除典型持久化管理器的额外层来简化与数据库的交互,并侧重于SQL的使用,而不是创建一种新的查询语言。

Additionally, it provides its own way of writing unit tests for the database interaction through the DBSpec class.

此外,它还通过DBSpec类提供了自己的方式来编写数据库交互的单元测试。

Let’s see how this library differs from other popular Java ORMs and how to use it.

让我们看看这个库与其他流行的Java ORM有什么不同,以及如何使用它。

2. ActiveJDBC vs Other ORMs

2.ActiveJDBC与其他ORMs的比较

ActiveJDBC has stark differences compared to most other Java ORMs. It infers the DB schema parameters from a database, thus removing the need for mapping entities to underlying tables.

与其他大多数Java ORM相比,ActiveJDBC有着明显的不同。它从数据库中推断出DB模式参数,因此不再需要将实体映射到底层表。

No sessions, no persistence managers, no need to learn a new query language, no getters/setters. The library itself is light in terms of size and number of dependencies.

没有会话,没有持久性管理器,不需要学习新的查询语言,没有getters/setters。该库本身在大小和依赖性数量方面都很轻。

This implementation encourages the usage of test databases which are cleaned up by the framework after executing the tests, thus reducing the cost of maintaining test databases.

这种实现方式鼓励使用测试数据库,在执行测试后,框架会对其进行清理,从而减少维护测试数据库的成本。

However, a little extra step of instrumentation is needed whenever we create or update model. We’ll discuss this in coming sections.

然而,每当我们创建或更新模型时,都需要额外的一点步骤仪器仪表。我们将在接下来的章节中讨论这个问题。

3. Design Principles

3.设计原则

  • Infers metadata from DB
  • Convention-based configuration
  • No sessions, no “attaching, re-attaching”
  • Lightweight Models, simple POJOs
  • No proxying
  • Avoidance of Anemic Domain Model
  • No need of DAOs and DTOs

4. Setting Up the Library

4.设置图书馆

A typical Maven setup for working with a MySQL database includes:

使用MySQL数据库的典型Maven设置包括。

<dependency>
    <groupId>org.javalite</groupId>
    <artifactId>activejdbc</artifactId>
    <version>1.4.13</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.34</version>
</dependency>

The latest version of activejdbc and mysql connector artifacts can be found on the Maven Central repository.

最新版本的activejdbcmysql connector工件可以在Maven Central仓库中找到。

Instrumentation is the price of simplification and needed when working with ActiveJDBC projects.

仪器仪表是简化的代价,在使用ActiveJDBC项目时需要。

There’s an instrumentation plugin which needs to be configured in the project:

有一个仪表插件,需要在项目中配置。

<plugin>
    <groupId>org.javalite</groupId>
    <artifactId>activejdbc-instrumentation</artifactId>
    <version>1.4.13</version>
    <executions>
        <execution>
            <phase>process-classes</phase>
            <goals>
                <goal>instrument</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The latest activejdbc-instrumentation plugin can also be found in Maven Central.

最新的activejdbc-instrumentation插件也可以在Maven中心找到。

And now, we can process instrumentation by doing one of these two commands:

而现在,我们可以通过执行这两个命令中的一个来处理仪表。

mvn process-classes
mvn activejdbc-instrumentation:instrument

5. Using ActiveJDBC

5.使用ActiveJDBC

5.1. The Model

5.1.模型

We can create a simple model with just one line of code – it involves extending the Model class.

我们只需要一行代码就可以创建一个简单的模型–这涉及到扩展Model类。

The library uses inflections of the English language to achieve conversions of plural and singular forms of nouns. This can be overridden using the @Table annotation.

该库使用英语的inflections来实现名词的复数和单数形式的转换。这可以使用@Table注解来覆盖。

Let’s see how a simple model looks like:

让我们看看一个简单的模型是什么样子的。

import org.javalite.activejdbc.Model;

public class Employee extends Model {}

5.2. Connecting to a Database

5.2.连接到一个数据库

Two classes – Base and DB – are provided to connect to databases.

提供了两个类–BaseDB–以连接到数据库.

The simplest way to connect to a database is:

连接到数据库的最简单方法是。

Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://host/organization", "user", "xxxxx");

When models are in operation, they utilize a connection found in the current thread. This connection is put on the local thread by the Base or DB class before any DB operation.

当模型处于运行状态时,它们利用在当前线程中发现的一个连接。这个连接是由BaseDB类在任何DB操作之前放在本地线程上。

The above approach allows for a more concise API, removing the need for DB Session or Persistence managers like in other Java ORMs.

上述方法允许一个更简洁的API,不再需要像其他Java ORM中的DB Session或Persistence管理器。

Let’s see how to use the DB class to connect to a database:

让我们看看如何使用DB类来连接到一个数据库

new DB("default").open(
  "com.mysql.jdbc.Driver", 
  "jdbc:mysql://localhost/dbname", 
  "root", 
  "XXXXXX");

If we look at how differently Base and DB are used to connect to databases, it helps us conclude that Base should be used if operating on a single database and DB should be used with multiple databases.

如果我们看看BaseDB用于连接数据库的方式有什么不同,这有助于我们得出结论:如果在单个数据库上操作,应该使用Base,而DB应该用于多个数据库。

5.3. Inserting Record

5.3.插入记录

Adding a record to the database is very simple. As mentioned before, there’s no need for setters and getters:

向数据库添加一条记录是非常简单的。如前所述,不需要设置器和获取器。

Employee e = new Employee();
e.set("first_name", "Hugo");
e.set("last_name", "Choi");
e.saveIt();

Alternatively, we can add the same record this way:

另外,我们也可以这样添加同样的记录。

Employee employee = new Employee("Hugo","Choi");
employee.saveIt();

Or even, fluently:

甚至,流利地表达。

new Employee()
 .set("first_name", "Hugo", "last_name", "Choi")
 .saveIt();

5.4. Updating Record

5.4.更新记录

The snippet below shows how to update a record:

下面的片段显示了如何更新一条记录。

Employee employee = Employee.findFirst("first_name = ?", "Hugo");
employee
  .set("last_name","Choi")
  .saveIt();

5.5. Deleting Record

5.5.删除记录

Employee e = Employee.findFirst("first_name = ?", "Hugo");
e.delete();

If there is a need to delete all records:

如果有必要删除所有记录。

Employee.deleteAll();

If we want to delete a record from a master table which cascades to child tables, use deleteCascade:

如果我们想从一个主表中删除一条记录,并将其级联到子表,请使用deleteCascade

Employee employee = Employee.findFirst("first_name = ?","Hugo");
employee.deleteCascade();

5.6. Fetching a Record

5.6.取出一条记录

Let’s fetch a single record from the database:

让我们从数据库中获取一条记录。

Employee e = Employee.findFirst("first_name = ?", "Hugo");

If we want to fetch multiple records, we can use the where method:

如果我们想获取多条记录,我们可以使用where方法。

List<Employee> employees = Employee.where("first_name = ?", "Hugo");

6. Transaction Support

6.事务支持

In Java ORMs, there is an explicit connection or a manager object (EntityManager in JPA, SessionManager in Hibernate, etc.). There’s no such thing in ActiveJDBC.

在Java ORM中,有一个明确的连接或一个管理对象(JPA中的EntityManager,Hibernate中的SessionManager,等等)。在ActiveJDBC中没有这样的东西。

The call Base.open() opens a connection, attaches it to the current thread and thus all subsequent methods of all models reuse this connection. The call Base.close() closes the connection and removes it from the current thread.

调用Base.open()打开一个连接,将其附加到当前线程,因此所有模型的后续方法都会重复使用这个连接。调用Base.close()关闭连接并将其从当前线程中移除。

To manage transactions, there are are few convenience calls:

为了管理交易,有一些方便的调用。

Starting a transaction:

开始一项交易。

Base.openTransaction();

Committing a transaction:

提交一个交易。

Base.commitTransaction();

Rolling back a transaction:

回滚一个交易。

Base.rollbackTransaction();

7. Supported Databases

7.支持的数据库

The latest version supports databases of likes SQLServer, MySQL, Oracle, PostgreSQL, H2, SQLite3, DB2.

最新版本支持喜欢SQLServer、MySQL、Oracle、PostgreSQL、H2、SQLite3、DB2的数据库。

8. Conclusion

8.结语

In this quick tutorial, we focused on and explored the very basics of ActiveJDBC.

在这个快速教程中,我们着重探讨了ActiveJDBC的基础知识。

As always, the source code related to this article can be found over on Github.

一如既往,与本文有关的源代码可以在Github上找到over