Integrating Spring Boot with HSQLDB – 将Spring Boot与HSQLDB集成

最后修改: 2018年 12月 30日

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

1. Overview

1.概述

Spring Boot makes it really easy to work with different database systems, without the hassle of manual dependency management.

Spring Boot使得与不同的数据库系统合作变得非常容易,而没有手动依赖性管理的麻烦。

More specifically, Spring Data JPA starter provides all the functionality required for seamless integration with several DataSource implementations.

更具体地说,Spring Data JPA启动程序提供了与若干数据源实现无缝集成所需的所有功能。

In this tutorial, we’ll learn how to integrate Spring Boot with HSQLDB.

在本教程中,我们将学习如何将Spring Boot与HSQLDB集成。

2. The Maven Dependencies

2.Maven的依赖性

To demonstrate how easy is to integrate Spring Boot with HSQLDB, we’ll create a simple JPA repository layer that performs CRUD operations on customers entities using an in-memory HSQLDB  database.

为了证明Spring Boot与HSQLDB的集成是多么容易,我们将创建一个简单的JPA资源库层,使用内存中的HSQLDB数据库对客户实体进行CRUD操作

Here’s the Spring Boot starter that we’ll use for getting our sample repository layer up and running:

这里是Spring Boot启动程序,我们将使用它来启动和运行我们的示例资源库层。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <version>2.4.0</version>
    <scope>runtime</scope>
</dependency>

Note that we’ve included the HSQLDB dependency as well. Without it, Spring Boot will try to automatically configure a DataSource bean and a JDBC connection pool for us through HikariCP.

请注意,我们也包含了HSQLDB依赖。如果没有它,Spring Boot将尝试通过HikariCP为我们自动配置一个DataSourcebean和一个JDBC连接池。

As a consequence, if we don’t specify a valid DataSource dependency in our pom.xml file, we’ll get a build failure.

因此,如果我们没有在pom.xml文件中指定一个有效的DataSource依赖,我们将得到一个构建失败

In addition, let’s make sure to check the latest version of spring-boot-starter-data-jpa on Maven Central.

此外,让我们确保检查Maven中心的spring-boot-starter-data-jpa的最新版本。

3. Connecting to an HSQLDB Database

3.连接到HSQLDB数据库

For exercising our demo repository layer, we’ll be using an in-memory database. It’s possible, however, to work with file-based databases as well. We’ll explore each of these methods in the sections below.

为了锻炼我们的演示资源库层,我们将使用一个内存数据库。然而,也有可能使用基于文件的数据库。我们将在下面的章节中分别探讨这些方法。

3.1. Running an External HSQLDB Server

3.1.运行一个外部HSQLDB服务器

Let’s take a look at how to get an external HSQLDB server running and create a file-based database. Installing HSQLDB and running the server is straightforward, overall.

让我们来看看如何让一个外部的HSQLDB服务器运行并创建一个基于文件的数据库。安装HSQLDB和运行服务器总体来说是很简单的。

Here are the steps that we should follow:

以下是我们应该遵循的步骤。

  • First, we’ll download HSQLDB and unzip it to a folder
  • Since HSQLDB doesn’t provide a default database out of the box, we’ll create one called “testdb” for example purposes
  • We’ll launch a command prompt and navigate to the HSQLDB data folder
  • Within the data folder, we’ll run the following command:
    java -cp ../lib/hsqldb.jar org.hsqldb.server.Server --database.0 file.testdb --dbname0.testdb
  • The above command will start the HSQLDB server and create our database whose source files will be stored in the data folder
  • We can make sure the database has been actually created by going to the data folder, which should contain a set of files called “testdb.lck”, “testdb.log”, “testdb.properties”, and “testdb.script” (the number of files varies depending on the type of database we’re creating)

Once the database has been set up, we need to create a connection to it.

一旦建立了数据库,我们需要创建一个连接到它。

To do this on Windows, let’s go to the database bin folder and run the runManagerSwing.bat file. This will open HSQLDB Database Manager’s initial screen, where we can enter the connection credentials:

要在Windows上这样做,让我们进入数据库bin文件夹,运行runManagerSwing.bat文件。这将打开HSQLDB数据库管理器的初始屏幕,在那里我们可以输入连接凭证。

  • Type: HSQL Database Engine
  • URL: jdbc:hsqldb:hsql://localhost/testdb
  • User: “SA” (System Administrator)
  • Password: leave the field empty

On Linux/Unix/Mac, we can use NetBeans, Eclipse, or IntelliJ IDEA to create the database connection through the IDE’s visual tools, using the same credentials.

在Linux/Unix/Mac上,我们可以使用NetBeans、Eclipse或IntelliJ IDEA,通过IDE的可视化工具创建数据库连接,使用相同的凭证。

In any of these tools, it’s straightforward to create a database table either by executing an SQL script in the Database Manager or within the IDE.

在任何这些工具中,通过在数据库管理器中或在集成开发环境中执行SQL脚本,都可以直接创建一个数据库表。

Once connected, we can create a customers table:

一旦连接,我们可以创建一个customers表。

CREATE TABLE customers (
   id INT  NOT NULL,
   name VARCHAR (45),
   email VARCHAR (45),      
   PRIMARY KEY (ID)
); 

In just a few easy steps, we’ve created a file-based HSQLDB database containing a customers table.

仅仅通过几个简单的步骤,我们就创建了一个基于文件的HSQLDB数据库,包含一个customers表。

3.2. The application.properties File

3.2.application.properties文件

If we wish to connect to the previous file-based database from Spring Boot, here are the settings that we should include in the application.properties file:

如果我们希望从Spring Boot连接到之前的基于文件的数据库,以下是我们应该在application.properties文件中包含的设置。

spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver 
spring.datasource.url=jdbc:hsqldb:hsql://localhost/testdb 
spring.datasource.username=sa 
spring.datasource.password= 
spring.jpa.hibernate.ddl-auto=update

Alternatively, if we use an in-memory database, we should use these:

另外,如果我们使用内存数据库,我们应该使用这些。

spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create

Please note the DB_CLOSE_DELAY=-1 parameter appended to the end of the database URL. When working with an in-memory database, we need to specify this, so the JPA implementation, which is Hibernate, won’t close the database while the application is running.

请注意附加在数据库URL末尾的DB_CLOSE_DELAY=-1参数。当使用内存数据库时,我们需要指定这个参数,这样JPA的实现,也就是Hibernate就不会在应用程序运行时关闭数据库

4. The Customer Entity

4、客户实体

With the database connection settings already set up,  next we need to define our Customer entity:

随着数据库连接设置的完成,接下来我们需要定义我们的Customer实体。

@Entity
@Table(name = "customers")
public class Customer {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    private String name;
    
    private String email;

    // standard constructors / setters / getters / toString
}

5. The Customer Repository

5.客户储存库

In addition, we need to implement a thin persistence layer, which allows us to have basic CRUD functionality on our Customer JPA entities.

此外,我们需要实现一个薄的持久层,它允许我们在Customer JPA实体上拥有基本的CRUD功能。

We can easily implement this layer by just extending the CrudRepository interface:

我们只需扩展CrudRepository接口,就能轻松实现这一层。

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long> {}

6. Testing the Customer Repository

6.测试客户存储库

Finally, we should make sure that Spring Boot can actually connect to HSQLDB. We can easily accomplish this by just testing the repository layer.

最后,我们应该确保Spring Boot能够真正连接到HSQLDB。我们只需测试存储库层,就能轻松实现这一目标。

Let’s start testing the repository’s findById() and findAll() methods:

让我们开始测试版本库的findById()findAll()方法。

@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryTest {
    
    @Autowired
    private CustomerRepository customerRepository;
    
    @Test
    public void whenFindingCustomerById_thenCorrect() {
        customerRepository.save(new Customer("John", "john@domain.com"));
        assertThat(customerRepository.findById(1L)).isInstanceOf(Optional.class);
    }
    
    @Test
    public void whenFindingAllCustomers_thenCorrect() {
        customerRepository.save(new Customer("John", "john@domain.com"));
        customerRepository.save(new Customer("Julie", "julie@domain.com"));
        assertThat(customerRepository.findAll()).isInstanceOf(List.class);
    }
}

Finally, let’s test the save() method:

最后,让我们测试一下save()方法。

@Test
public void whenSavingCustomer_thenCorrect() {
    customerRepository.save(new Customer("Bob", "bob@domain.com"));
    Customer customer = customerRepository.findById(1L).orElseGet(() 
      -> new Customer("john", "john@domain.com"));
    assertThat(customer.getName()).isEqualTo("Bob");
}

7. Conclusion

7.结论

In this article, we learned how to integrate Spring Boot with HSQLDB, and how to use either a file-based or in-memory database in the development of a basic JPA repository layer.

在这篇文章中,我们学习了如何将Spring Boot与HSQLDB集成,以及如何在开发基本的JPA资源库层时使用基于文件或内存的数据库。

As usual, all the code samples shown in this article are available over on GitHub.

像往常一样,本文中显示的所有代码样本都可以在GitHub上获得。