ZetCode

RESTEasy 初始化 H2 数据库脚本

最后修改于 2023 年 1 月 10 日

RESTEasy 初始化 H2 数据库脚本教程展示了如何在 RESTEasy 创建的 RESTful Web 应用程序中初始化数据库脚本。

RESTEasy

RESTEasy 是一个用于开发 RESTful Web 服务的 Java 框架。它是 JAX-RS 2.0 规范的一个完全认证和可移植的实现。JAX-RS 2.0 规范是一个 JCP(Java Community Process)规范,它为 HTTP 协议上的 RESTful Web 服务提供了一个 Java API。

RESTEasy 可以在任何 Servlet 容器中运行。

Web 监听器

Web 监听器跟踪 Web 应用程序中的关键事件。它们允许高效的资源管理和基于事件状态的自动化处理。Web 监听器在 web.xml 部署描述符中或使用 @WebListener 注解声明。

RESTEasy 初始化数据库脚本示例

下面的示例是一个简单的 RESTful 应用程序,它将城市列表作为 JSON 数据返回给客户端。数据在应用程序启动时在 Web 监听器中加载。有两个脚本:schema.sql 创建表,data.sql 向表中插入数据。

$ tree
.
├── nb-configuration.xml
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── zetcode
        │           ├── conf
        │           │   ├── AppConfig.java
        │           │   └── MyAppInitializer.java
        │           ├── model
        │           │   └── City.java
        │           ├── resource
        │           │   └── MyResource.java
        │           └── service
        │               ├── CityService.java
        │               └── ICityService.java
        ├── resources
        │   └── sql
        │       ├── data.sql
        │       └── schema.sql
        └── webapp
            ├── META-INF
            │   └── context.xml
            └── WEB-INF
                └── beans.xml

这是项目结构。

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>RestEasyLoadScripts</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>RestEasyLoadScripts</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        
        <!-- Set up RESTEasy-->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>3.1.4.Final</version>
        </dependency>
        
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-servlet-initializer</artifactId>
            <version>3.1.4.Final</version>
        </dependency>    
           
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson-provider</artifactId>
            <version>3.1.4.Final</version>
        </dependency>          
                    
        <!-- CDI for RESTEasy-->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-cdi</artifactId>
            <version>3.1.4.Final</version>
        </dependency>       
        
        <dependency>
            <groupId>org.jboss.weld.servlet</groupId>
            <artifactId>weld-servlet-shaded</artifactId>
            <version>3.0.2.Final</version>
        </dependency>                       
        
        <!-- Spring JdbcTemplate -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>
            
        <!-- H2 driver -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.196</version>
        </dependency>
        
        <!-- Needed for @WebListener -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
            <scope>provided</scope>
        </dependency>       

    </dependencies>
    
    <build>
        <plugins>
            
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

        </plugins>
    </build>    

</project>

这是 Maven POM 文件。它包含了 RESTEasy、RESTEasy 的 CDI、Jackson 提供者、H2 驱动程序、Spring JdbcTemplate 和 Java Servlets(用于 Web 监听器)的依赖项。

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/RestEasyLoadScripts"/>

在 Tomcat 的 context.xml 配置文件中,我们定义了应用的上下文路径。

beans.xml
<?xml version="1.0"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">

</beans>

使用 CDI 的应用程序必须定义一个 beans.xml 文件。它可以是空的,就像我们的情况一样。对于 Web 应用程序,beans.xml 文件必须位于 WEB-INF 目录中。对于 EJB 模块或 JAR 文件,beans.xml 文件必须位于 META-INF 目录中。

schema.sql
CREATE TABLE cities(id INT PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(100), population INT);

schema.sql 创建数据库 schema。

data.sql
INSERT INTO cities(name, population) VALUES('Bratislava', 432000);
INSERT INTO cities(name, population) VALUES('Budapest', 1759000);
INSERT INTO cities(name, population) VALUES('Prague', 1280000);
INSERT INTO cities(name, population) VALUES('Warsaw', 1748000);
INSERT INTO cities(name, population) VALUES('Los Angeles', 3971000);
INSERT INTO cities(name, population) VALUES('New York', 8550000);
INSERT INTO cities(name, population) VALUES('Edinburgh', 464000);
INSERT INTO cities(name, population) VALUES('Berlin', 3671000);

data.sql 向数据库表中插入数据。

AppConfig.java
package com.zetcode.conf;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("rest")
public class AppConfig extends Application {

}

这是应用程序配置类。Application 定义了 JAX-RS 应用程序的组件并提供额外的元数据。

@ApplicationPath("rest")

使用 @ApplicationPath 注解,我们设置了 RESTful Web 服务的路径。

MyAppInitializer.java
package com.zetcode.conf;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

@WebListener
public class MyAppInitializer implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        Logger lgr = Logger.getLogger(MyAppInitializer.class.getName());
        lgr.log(Level.INFO, "executing contextInitialized()");

        String url = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;" 
                + "INIT=RUNSCRIPT FROM 'classpath:/sql/schema.sql'"
                + "\\;RUNSCRIPT FROM 'classpath:/sql/data.sql'";

        SimpleDriverDataSource ds = new SimpleDriverDataSource();
        ds.setDriver(new org.h2.Driver());
        ds.setUrl(url);

        try (Connection con = ds.getConnection()) {

        } catch (SQLException ex) {
            lgr.log(Level.SEVERE, ex.getMessage(), ex);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
}

数据库脚本在 Web 监听器中初始化。

@WebListener
public class MyAppInitializer implements ServletContextListener {

@WebListener 注解用于声明一个 Web 监听器。

@Override
public void contextInitialized(ServletContextEvent sce) {

当 Web 应用程序初始化开始时,会调用 ServletContextListener'scontextInitialized 方法。

String url = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;" 
        + "INIT=RUNSCRIPT FROM 'classpath:/sql/schema.sql'"
        + "\\;RUNSCRIPT FROM 'classpath:/sql/data.sql'";

在此连接字符串 URL 中,我们创建了一个名为 testdb 的内存数据库。DB_CLOSE_DELAY 会在虚拟机存活期间保留内存数据库的内容。否则,当连接关闭时,数据库将被删除。RUNSCRIPT 命令执行数据库脚本。

SimpleDriverDataSource ds = new SimpleDriverDataSource();
ds.setDriver(new org.h2.Driver());
ds.setUrl(url);

我们设置了一个 SimpleDriverDataSource。它是一个不支持连接池的简单数据源。它为每次调用创建一个新连接。

try (Connection con = ds.getConnection()) {

} catch (SQLException ex) {
    lgr.log(Level.SEVERE, ex.getMessage(), ex);
}

通过创建连接,数据库脚本将被执行。

City.java
package com.zetcode.model;

import java.util.Objects;

public class City {

    private Long id;
    private String name;
    private int population;

    public City() {
    }

    public City(String name, int population) {
        this.name = name;
        this.population = population;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 71 * hash + Objects.hashCode(this.id);
        hash = 71 * hash + Objects.hashCode(this.name);
        hash = 71 * hash + this.population;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final City other = (City) obj;
        if (this.population != other.population) {
            return false;
        }
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        return Objects.equals(this.id, other.id);
    }
    
    @Override
    public String toString() {
        
        StringBuilder builder = new StringBuilder();
        builder.append("City{id=").append(id).append(", name=")
                .append(name).append(", population=")
                .append(population).append("}");
        
        return builder.toString();
    }
}

这是一个 City 模型类。它包含三个属性:idnamepopulation

ICityService.java
package com.zetcode.service;

import com.zetcode.model.City;
import java.util.List;

public interface ICityService {
    
    public List<City> findAll();
}

ICityService 包含 findAll 合约方法。

CityService.java
package com.zetcode.service;

import com.zetcode.model.City;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

public class CityService implements ICityService {

    @Override
    public List<City> findAll() {

        SimpleDriverDataSource ds = new SimpleDriverDataSource();
        ds.setDriver(new org.h2.Driver());
        ds.setUrl("jdbc:h2:mem:testdb");

        String query = "SELECT * FROM cities;";

        JdbcTemplate jtm = new JdbcTemplate(ds);
        List<City> cities = jtm.query(query, 
                new BeanPropertyRowMapper(City.class));

        return cities;
    }
}

CityService 包含 findAll 方法的实现。它从 testdb 内存数据库检索所有城市对象。

MyResource.java
package com.zetcode.resource;

import com.zetcode.model.City;
import com.zetcode.service.ICityService;
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("cities")
public class MyResource {
    
    @Inject 
    private ICityService cityService;
    
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<City> message() {
        
        List<City> cities = cityService.findAll();

        return cities;
    }
}

这是 MyResource 类。

@Path("cities")
public class MyResource {

@Path 指定资源响应的 URL。

@Inject 
private ICityService cityService;

使用 @Inject 注解,我们将 city service 对象注入到 cityService 字段中。

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<City> message() {
    
    List<City> cities = cityService.findAll();

    return cities;
}

@GET 注解表示被注解的方法响应 HTTP GET 请求。使用 @Produces 注解,我们定义该方法生成 JSON。我们调用一个服务方法并返回一个城市列表。消息体写入器将 Java 类转换为 JSON 并将其写入响应体。

$ curl localhost:8084/RestEasyLoadScripts/rest/cities
[{"id":1,"name":"Bratislava","population":432000},{"id":2,"name":"Budapest","population":1759000},
{"id":3,"name":"Prague","population":1280000},{"id":4,"name":"Warsaw","population":1748000},
{"id":5,"name":"Los Angeles","population":3971000},{"id":6,"name":"New York","population":8550000},
{"id":7,"name":"Edinburgh","population":464000},{"id":8,"name":"Berlin","population":3671000}]

将应用程序部署到 Tomcat 后,我们使用 curl 向应用程序发送一个 GET 请求。我们获取在数据库初始化脚本中创建的数据。

在本教程中,我们展示了如何使用 RESTEasy 和 H2 数据库在一个简单的 RESTful 应用程序中创建数据库初始化脚本。我们使用 Spring 的 JdbcTemplate 连接到 H2。该应用程序已部署到 Tomcat。