Use JFinal to connect to OceanBase Cloud

2026-01-21 03:00:30  Updated

This topic describes how to use the JFinal framework to connect to OceanBase Cloud and perform basic operations such as creating a table, inserting data, and querying data.

Prerequisites

  • You have registered an account for OceanBase Cloud, created an instance and an Oracle-compatible tenant. For more information, see Create an instance and Create a tenant.
  • You have installed JDK 1.8 and Maven.
  • You have installed IntelliJ IDEA.

Note

The code examples in this topic are run in IntelliJ IDEA 2021.3.2 (Community Edition). You can also use other tools that you prefer to run the code examples.

Procedure

Note

The steps provided in this topic are based on the Windows environment. If you are using a different operating system or compiler, the steps may vary slightly.

  1. Obtain the connection string of OceanBase Cloud.
  2. Import the java-oceanbase-Jfinal project into IDEA.
  3. Set up the Tomcat environment for the java-oceanbase-Jfinal project.
  4. Modify the database connection information in the java-oceanbase-Jfinal project.
  5. Run the java-oceanbase-Jfinal project.

Step 1: Obtain the connection string of the OceanBase Cloud database

  1. Log in to the OceanBase Cloud console. In the instance list, expand the information of the target instance, and in the target tenant, choose Connect > Get Connection String.

    For more information, see Obtain the connection string.

  2. Fill in the URL with the information of the created OceanBase Cloud database.

    Note

    The URL information is required in the config.properties file.

    jdbc:oceanbase://host:port/schema_name?user=$user_name&password=$password
    

    Parameter description:

    • $host: the connection address of the OceanBase Cloud database, for example, t********.********.oceanbase.cloud.
    • $port: the connection port of the OceanBase Cloud database. The default value is 1521.
    • $schema_name: the name of the schema to be accessed.
    • $user_name: the account for accessing the database.
    • $password: the password of the account.

For more information about the URL parameters, see Database URL.

Step 2: Import the java-oceanbase-Jfinal project into IDEA

  1. Open IntelliJ IDEA and choose File > Open....

    file

  2. In the Open File or Project window that appears, select the project file and click OK.

  3. IntelliJ IDEA automatically identifies various files in the project and displays the project directory structure, file list, module list, and dependency relationships in the Project tool window. The Project tool window is usually located on the left side of the IntelliJ IDEA interface and is open by default. If it is closed, you can click View > Tool Windows > Project in the menu bar or press Alt + 1 to open it.

    Note

    When you import a project using IntelliJ IDEA, it automatically detects the pom.xml file in the project, downloads the required dependency libraries based on the described dependencies in the file, and adds them to the project.

  4. View the project.

    Jfinal

Step 3: Set up the Tomcat runtime environment for the java-oceanbase-Jfinal project

  1. Download Tomcat 8.5.95. Download the Tomcat 8.5.95 compressed package from the Apache Tomcat official website and decompress it to the directory where you want to install Tomcat.

  2. Configure Tomcat in IDEA. Open IntelliJ IDEA, choose Settings > Plugins from the File menu. In the search box in the middle of the Settings window, search for Smart Tomcat, download it, and choose Apply. The Tomcat Server tab appears at the bottom of the left side of the Settings window. Enter the Tomcat Server tab, click the + button on the right, select the decompressed Tomcat directory, click Apply, and then click OK.

    Tomcat server

  3. Create a Tomcat run configuration.

    In the top toolbar of IDEA, choose Run > Edit Configurations. In the Run/Debug Configurations window, click + and select Tomcat Server. Enter the server name in the Name field, select the installed Tomcat version in the Configuration drop-down list, set the Context path to /, and set the SSL port to 8080. In the Before launch drop-down list, click + and select Launch Web Browser. Enter the URL http://localhost:8080/hello/getData in the Edit field. Click Apply and then OK.

    apache tomcat8.5.95

  4. Run the Tomcat server.

    In the top toolbar of IDEA, select the Tomcat run configuration that you just created. Click the green triangle button to start the Tomcat server. You can view the startup log of the Tomcat server in the Run window of IDEA.

Step 4: Modify the database connection information in the java-oceanbase-Jfinal project

Modify the database connection information in the config.properties file based on the information obtained in Step 1: Obtain the connection string of the OceanBase Cloud database.

Here is an example:

  • The name of the database driver is com.oceanbase.jdbc.Driver.
  • The connection address of the OceanBase Cloud database is t5******.********.oceanbase.cloud.
  • The port is 1521.
  • The name of the schema to be accessed is sys.
  • The tenant account is oracle001.
  • The password is ******. Here is the sample code:
db.app.driver=com.oceanbase.jdbc.Driver
db.app.url=jdbc:oceanbase://t5******.********.oceanbase.cloud:1521/sys
db.app.user=oracle001
db.app.password=******
db.app.poolInitialSize=3
db.app.poolMaxSize=10
db.app.connectionTimeoutMillis=100
db.app.validationQuery=select 1 from dual

Step 5: Run the java-oceanbase-Jfinal project

  1. Run the project.

    In the top toolbar of IDEA, select the Tomcat run configuration that you just created. Click the green triangle button to start the Tomcat server. Open the path http://localhost:8080/hello/getData in Google or Internet Explorer to view the running results.

  2. View the running results.

    [{"ID":1,"NAME":"John"},{"ID":2,"NAME":"Jane"}]
    

Project code

Click java-oceanbase-Jfinal to download the project code. This is a compressed package named java-oceanbase-Jfinal.

After decompressing it, you will find a folder named java-oceanbase-Jfinal. The directory structure is as follows:

│--pom.xml
│
├─.idea
│
├─src
│  ├─main
│  │  ├─java
│  │  │  └─com
│  │  │      └─oceanbase
│  │  │          └─testjfinal
│  │  │              ├─config
│  │  │              │   └─UserConfig.java
│  │  │              │
│  │  │              ├─controller
│  │  │              │   └─UserController.java
│  │  │              │
│  │  │              └─pojo
│  │  │                  └─User.java
│  │  │
│  │  ├─resources
│  │  │    └─config.properties
│  │  │    
│  │  └─webapp    
│  │      └─WEB-INF
│  │          └─web.xml
│  │             
│  │                
│  │
│  └─test
│      └─java
│         
│
└─target

File description:

  • pom.xml: the configuration file of the Maven project. It contains information about the project's dependencies, plugins, and build process.
  • .idea: a directory used in the IDE (Integrated Development Environment) to store project-related configuration information.
  • src: a directory typically used to store the source code of the project.
  • main: a directory that stores the main source code and resource files.
  • java: a directory that stores the Java source code.
  • com: the root directory for storing Java packages.
  • oceanbase: the root directory for storing the project.
  • testjfinal: a directory that stores the code related to the JFinal framework.
  • config: a directory that stores the configuration files of the application.
  • UserConfig.java: the user configuration class file.
  • controller: a directory that stores the controller class files of the application.
  • UserController.java: the user controller class file.
  • pojo: a directory that stores the JavaBean or entity classes.
  • User.java: the user entity class file.
  • resources: a directory that stores resource files, such as configuration files and SQL files.
  • config.properties: the configuration file that stores the database connection information.
  • webapp: the directory of the Web application, which stores the static resources and configuration files of the Web application.
  • WEB-INF: the WEB-INF directory of the Web application, which stores the configuration files and other protected resource files.
  • web.xml: the deployment descriptor file of the Web application.
  • test: a directory that stores the test code and resource files.
  • target: a directory that stores the compiled Class files, Jar packages, and other files.

Introduction to the pom.xml file

Note

If you want to verify the example, you can use the default code without any modifications. You can also modify the pom.xml file as needed based on the following instructions.

The content of the pom.xml configuration file is as follows:

  1. File declaration statement.

    This statement declares the file as an XML file using XML version 1.0 and character encoding UTF-8.

    Sample code:

    <?xml version="1.0" encoding="UTF-8"?>
    
  2. Configure the namespaces and model version of the POM.

    1. Use xmlns to set the POM namespace to http://maven.apache.org/POM/4.0.0.
    2. Use xmlns:xsi to set the XML namespace to http://www.w3.org/2001/XMLSchema-instance.
    3. Use xsi:schemaLocation to set the POM namespace to http://maven.apache.org/POM/4.0.0 and the location of the POM XSD file to http://maven.apache.org/xsd/maven-4.0.0.xsd.
    4. Use <modelVersion> to set the POM model version used by the POM file to 4.0.0.

    Sample code:

    <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>
    </project>
    
  3. Configure basic information.

    1. Use <groupId> to set the project identifier to com.oceanbase.
    2. Use <artifactId> to set the project dependency to java-oceanbase-jfinal.
    3. Use <version> to set the project version to 1.0-SNAPSHOT.
    4. Use <packaging> to set the project packaging method to WAR (Web Application Archive).

    Sample code:

     <groupId>com.oceanbase</groupId>
     <artifactId>java-oceanbase-jfinal</artifactId>
     <version>1.0-SNAPSHOT</version>
     <!-- Packaging method (default to jar) -->
     <packaging>war</packaging>
    
  4. Configure the Maven version.

    Use <maven.compiler.source> and <maven.compiler.target> to set the source code version and target code version of the compiler to Java 8.

    Sample code:

     <properties>
         <maven.compiler.source>8</maven.compiler.source>
         <maven.compiler.target>8</maven.compiler.target>
     </properties>
    
  5. Configure core dependencies.

    1. Set the organization of the dependency to com.jfinal, the name to jfinal, and the version to 5.0.6. This dependency allows you to use the features of the JFinal framework.

      Sample code:

      <dependency>
          <groupId>com.jfinal</groupId>
          <artifactId>jfinal</artifactId>
          <version>5.0.6</version>
      </dependency>
      
    2. Set the organization of the dependency to com.alibaba, the name to druid, and the version to 1.2.8. This dependency allows you to use the Druid library for managing and optimizing database connection acquisition and release.

      Sample code:

      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.2.8</version>
      </dependency>
      
    3. Set the organization of the dependency to com.oceanbase, the name to oceanbase-client, and the version to 2.4.3. This dependency allows you to use the client features provided by OceanBase, such as connection, query, and transaction.

      Sample code:

          <dependencies>
          <dependency>
              <groupId>com.oceanbase</groupId>
              <artifactId>oceanbase-client</artifactId>
              <version>2.4.3</version>
          </dependency>
          </dependencies>
      

Introduction to the config.properties file

The config.properties file configures the database connection information required to connect to the cloud database on OceanBase Cloud. This includes the class name of the database driver, the connection URL, the username, the password, and the connection pool settings. These configuration items are used to obtain and manage database connections in the application for database operations.

  • Use db.app.driver to set the database driver to com.oceanbase.jdbc.Driver, which is used to establish a connection with the cloud database on OceanBase Cloud.

  • Use db.app.url to set the URL for connecting to the database.

  • Use db.app.user to set the username for connecting to the database.

  • Use db.app.password to set the password for connecting to the database.

  • Use db.app.poolInitialSize to set the initial size of the database connection pool to 3, meaning that 3 database connections are created initially.

  • Use db.app.poolMaxSize to set the maximum size of the database connection pool to 10, meaning that up to 10 database connections can be created in the pool.

  • Use db.app.connectionTimeoutMillis to set the timeout for database connections to 100 ms, meaning that if a connection is not obtained within 100 ms, a timeout exception is thrown.

  • Use db.app.validationQuery to set the SQL query statement for validating database connections to select 1 from dual, meaning that this query is executed when a connection is obtained from the connection pool to verify its validity.

    Sample code:

      db.app.driver=com.oceanbase.jdbc.Driver
      db.app.url=jdbc:oceanbase://host:port/schema_name
      db.app.user=user_name
      db.app.password=******
      db.app.poolInitialSize=3
      db.app.poolMaxSize=10
      db.app.connectionTimeoutMillis=100
      db.app.validationQuery=select 1 from dual
    

Introduction to the web.xml file

The web.xml file is used to configure filters for a Web application.

The content of the web.xml configuration file is as follows:

  1. A file declaration statement.

    This statement declares the file as an XML file using XML version 1.0 and character encoding UTF-8.

    Sample code:

    <?xml version="1.0" encoding="UTF-8"?>
    
  2. Configure the XML namespace and XML model version.

    1. Use xmlns:xsi to specify the XML namespace as http://www.w3.org/2001/XMLSchema-instance.
    2. Use xmlns to specify the XML namespace as http://java.sun.com/xml/ns/javaee.
    3. Use xsi:schemaLocation to specify the XML namespace as http://java.sun.com/xml/ns/javaee and the location of the XML XSD file as http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd.
    4. Use the <id> and <version> elements to specify the ID of the Web application as WebApp_ID and the version number as 3.0.

    Sample code:

     <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
              xmlns="http://java.sun.com/xml/ns/javaee" 
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
              id="WebApp_ID" 
              version="3.0">
    
  3. Configure the JFinal filter.

    A filter named jfinal is configured to use the JFinal framework in the Web application. The class of the filter is specified as com.jfinal.core.JFinalFilter. The initialization parameter configClass is specified to indicate the location of the configuration class for the JFinal framework as com.oceanbase.testjfinal.config.UserConfig. This filter is used to use the JFinal framework in the Web application and configure the behavior of the JFinal framework based on the specified configuration class.

    Sample code:

     <filter>
         <filter-name>jfinal</filter-name>
         <filter-class>com.jfinal.core.JFinalFilter</filter-class>
         <init-param>
             <param-name>configClass</param-name>
             <!-- your jfinal configuration location -->
             <param-value>com.oceanbase.testjfinal.config.UserConfig</param-value>
         </init-param>
     </filter>
    
  4. Configure the mapping of the JFinal filter.

    Apply the jfinal filter to all request paths, meaning the filter will be applied to all requests in the application.

    Sample code:

     <filter-mapping>
         <filter-name>jfinal</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>
    

UserConfig.java

The UserConfig.java file is used to configure the routing, plugins, database connections, and other related information of an application.

The code in the UserConfig.java file mainly includes the following parts:

  1. Import other classes and interfaces.

    Declare the interfaces and classes included in the current file:

    • StatFilter class: used to statistics the performance of database access.
    • JdbcConstants class: used to define constants for database types.
    • WallFilter class: used to prevent SQL injection attacks.
    • PropKit class: used to read configuration files.
    • ActiveRecordPlugin class: used to operate databases.
    • Db class: used to execute database operations.
    • OracleDialect class: used to specify the dialect of a database.
    • DruidPlugin class: used to connect to a database.
    • Engine class: used to configure a template engine.
    • UserController class: used to handle requests related to users.
    • User class: used to pass and store user data.

    Sample code:

    import com.alibaba.druid.filter.stat.StatFilter;
    import com.alibaba.druid.util.JdbcConstants;
    import com.alibaba.druid.wall.WallFilter;
    import com.jfinal.config.*;
    import com.jfinal.kit.PropKit;
    import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
    import com.jfinal.plugin.activerecord.Db;
    import com.jfinal.plugin.activerecord.dialect.OracleDialect;
    import com.jfinal.plugin.druid.DruidPlugin;
    import com.jfinal.template.Engine;
    import com.oceanbase.testjfinal.controller.UserController;
    import com.oceanbase.testjfinal.pojo.User;
    
  2. Define the UserConfig class.

    By overriding the methods of the JFinalConfig class, you can configure constants, routing, plugins, and database connections.

    1. Define the configConstant method.

      This method is used to configure constants of the JFinal framework. It uses the PropKit class to read configurations from the configuration file.

      Sample code:

      @Override
      public void configConstant(Constants constants) {
          PropKit.use("config.properties");
      }
      
    2. Define the configRoute method.

      This method is used to configure route mappings. It uses the routes.add method to map the "/hello" path to the default access page of the UserController class.

      Sample code:

      @Override
      public void configRoute(Routes routes) {
          routes.add("/hello", UserController.class, "/");
      }
      
    3. Define the configEngine method.

      This method is used to configure a template engine.

      Sample code:

      @Override
      public void configEngine(Engine engine) {
      }
      
    4. Define the configPlugin method.

      This method is used to configure plugins of an application. It initializes database connections and table structures by calling the init method, creates the DruidPlugin and ActiveRecordPlugin plugins, and adds them to the plugins list. It also adds the mapping between database tables and entity classes by calling the addMapping method of the activeRecordPlugin class, and maps the TEST_USER table to the User class.

      Sample code:

      @Override
      public void configPlugin(Plugins plugins) {
          init();
          DruidPlugin druidPlugin = createDruidPlugin();
          plugins.add(druidPlugin);
      
          ActiveRecordPlugin activeRecordPlugin = createActiveRecordPlugin(druidPlugin);
          activeRecordPlugin.addMapping("TEST_USER", User.class);
          plugins.add(activeRecordPlugin);
      }
      
    5. Define the createDruidPlugin method.

      This method is used to create the DruidPlugin plugin and configure related parameters, including the connection pool size, SQL firewall, and connection error handling.

      • It calls the get method of the PropKit class to obtain database connection-related attribute values from the configuration file, including the URL, username, password, and driver class. Then, it creates a DruidPlugin object and initializes it using the obtained attribute values.

      • It calls the addFilter method to add a StatFilter instance to the DruidPlugin object. The StatFilter instance is used to statistics the performance of database access. It creates a WallFilter instance, sets the database type to OceanBase by calling the setDbType method, and adds the WallFilter instance to the DruidPlugin object for SQL firewall filtering.

      • It calls the setInitialSize method to set the initial size of the connection pool; the setMaxPoolPreparedStatementPerConnectionSize method to set the maximum number of prepared statements per connection pool; the setTimeBetweenConnectErrorMillis method to set the time interval between two connection errors; and the setValidationQuery method to set the connection validation query statement. Finally, it returns the created DruidPlugin instance.

        Sample code:

        private DruidPlugin createDruidPlugin() {
            DruidPlugin druidPlugin = new DruidPlugin(
                    PropKit.get("db.app.url"),
                    PropKit.get("db.app.user"),
                    PropKit.get("db.app.password"),
                    PropKit.get("db.app.driver")
            );
        
            druidPlugin.addFilter(new StatFilter());
            WallFilter wallFilter = new WallFilter();
            wallFilter.setDbType(JdbcConstants.OCEANBASE);
            druidPlugin.addFilter(wallFilter);
        
            druidPlugin.setInitialSize(PropKit.getInt("db.app.poolInitialSize"));
            druidPlugin.setMaxPoolPreparedStatementPerConnectionSize(PropKit.getInt("db.app.poolMaxSize"));
            druidPlugin.setTimeBetweenConnectErrorMillis(PropKit.getInt("db.app.connectionTimeoutMillis"));
            druidPlugin.setValidationQuery("select 1 from dual");
        
            return druidPlugin;
        }
        
    6. Define the init method.

      This method is used to initialize database connections and create database tables. It calls the initDbConnection method to initialize database connections and returns an ActiveRecordPlugin instance. It then executes an SQL statement to query whether the TEST_USER user table exists. If the TEST_USER user table does not exist, it executes the CREATE TABLE statement to create a database table named TEST_USER, which contains the ID and NAME fields. Finally, it closes the connection of the ActiveRecordPlugin plugin to release the database connection.

      Sample code:

      public void init() {
          ActiveRecordPlugin arp = initDbConnection();
          boolean tableExists = Db.queryInt("SELECT COUNT(*) FROM USER_TABLES WHERE TABLE_NAME = 'TEST_USER'") > 0;
          if (!tableExists) {
              String sql = "CREATE TABLE TEST_USER (ID NUMBER(10), NAME VARCHAR2(50))";
              Db.update(sql);
          }
          arp.stop();
      }
      
    7. Define the initDbConnection method.

      This method is used to initialize database connections. It first calls the createDruidPlugin method to create a DruidPlugin object and assigns it to the druidPlugin variable. The createDruidPlugin method is responsible for creating and configuring the DruidPlugin object for managing the database connection pool. It then calls the createActiveRecordPlugin method to create an ActiveRecordPlugin object and passes the DruidPlugin object as a parameter to this method. The createActiveRecordPlugin method is responsible for creating and configuring the ActiveRecordPlugin object for managing database operations. It then calls the druidPlugin.start method to start the DruidPlugin object and initialize the database connection pool. Finally, it calls the activeRecordPlugin.start method to start the ActiveRecordPlugin object, which initializes the relevant settings for database operations based on the configuration.

      Sample code:

      private ActiveRecordPlugin initDbConnection() {
          DruidPlugin druidPlugin = createDruidPlugin();
          ActiveRecordPlugin activeRecordPlugin = createActiveRecordPlugin(druidPlugin);
      
          druidPlugin.start();
          activeRecordPlugin.start();
      
          return activeRecordPlugin;
      }
      
    8. Define the ConfigInterceptor and ConfigHandler methods.

      These methods are used for global configuration during system initialization.

      Sample code:

      @Override
      public void configInterceptor(Interceptors interceptors) {
      }
      
      @Override
      public void configHandler(Handlers handlers) {
      }
      

Introduction to the UserController.java file

The UserController.java file inserts data into the database and queries data using the getData method, and returns the query results in JSON format to the client. It uses the Db class provided by the JFinal framework to perform database operations and the custom User class for data mapping to achieve database operations and data return functionality.

The code in the UserController.java file mainly includes the following parts:

  1. Import other classes and interfaces.

    Declare the interfaces and classes included in the current file:

    • Controller class: used to handle requests and responses.
    • Db class: used to perform database operations.
    • User class: used to map database tables.
    • List interface: used to operate on query result sets.

    Code:

    import com.jfinal.core.Controller;
    import com.jfinal.plugin.activerecord.Db;
    import com.oceanbase.testjfinal.pojo.User;
    
    import java.util.List;
    
  2. Define the UserController class.

    Provide a controller for the JFinal framework and use the getData method to perform data insertion and query operations on the database.

    1. Insert data. Use the Db.update method to execute an SQL insert statement and insert two data records into the TEST_USER table with IDs 1 and 2, and names John and Jane, respectively.
    2. Query data. Use the User.dao.find method to execute an SQL query statement and query all data from the TEST_USER table. The query results are assigned to a List type variable named users.
    3. Render JSON data. Use the renderJson method to render the data stored in the users object into JSON format and return it to the client.
    4. Exception handling. If an exception is captured during the execution, the exception stack information is printed using the catch statement block.

    Code:

    public class UserController extends Controller {
        public void getData(){
    
            try {
    
                // Insert data
                String insertDataSql = "INSERT INTO TEST_USER (ID, NAME) VALUES (?, ?)";
                Db.update(insertDataSql, 1, "John");
                Db.update(insertDataSql, 2, "Jane");
                // Query data
                List<User> users;
                users = User.dao.find("SELECT * FROM TEST_USER");
                renderJson(users);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    
    }
    

Introduction to the User.java file

The User.java file is used to implement the mapping between database tables and Java objects.

The code in the User.java file mainly includes the following parts:

  1. Import the Model class.

    The Model class is used to map database tables and operate on data.

  2. Define the User class.

    The User class uses the methods provided by the inherited Model class to perform database operations.

    Code:

    import com.jfinal.plugin.activerecord.Model;
    
    
        public class User extends Model<User> {
            public static final User dao = new User();
    
    }
    

Complete code

pom.xml
config.properties
web.xml
UserConfig.java
UserController.java
User.java
<?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.oceanbase</groupId>
    <artifactId>java-oceanbase-jfinal</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!-- Packaging method (default to jar) -->
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.jfinal</groupId>
            <artifactId>jfinal</artifactId>
            <version>5.0.6</version>
        </dependency>


        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <dependency>
            <groupId>com.oceanbase</groupId>
            <artifactId>oceanbase-client</artifactId>
            <version>2.4.3</version>
        </dependency>
    </dependencies>
</project>
db.app.driver=com.oceanbase.jdbc.Driver
db.app.url=jdbc:oceanbase://host:port/schema_name
db.app.user=user_name
db.app.password=
db.app.poolInitialSize=3
db.app.poolMaxSize=10
db.app.connectionTimeoutMillis=100
db.app.validationQuery=select 1 from dual
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <filter>
        <filter-name>jfinal</filter-name>
        <filter-class>com.jfinal.core.JFinalFilter</filter-class>
        <init-param>
            <param-name>configClass</param-name>
            <!-- your jfinal configuration location -->
            <param-value>com.oceanbase.testjfinal.config.UserConfig</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>jfinal</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
package com.oceanbase.testjfinal.config;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.config.*;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.dialect.OracleDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.Engine;
import com.oceanbase.testjfinal.controller.UserController;
import com.oceanbase.testjfinal.pojo.User;

public class UserConfig extends JFinalConfig {
    @Override
    public void configConstant(Constants constants) {
        // Read properties configuration
        PropKit.use("config.properties");
    }

    @Override
    public void configRoute(Routes routes) {
        // Set the default access page for project startup, which does not need to be set in the web.
        routes.add("/hello", UserController.class, "/");
    }

    @Override
    public void configEngine(Engine engine) {
    }

    @Override
    public void configPlugin(Plugins plugins) {
        init();
        DruidPlugin druidPlugin = createDruidPlugin();
        plugins.add(druidPlugin);

        ActiveRecordPlugin activeRecordPlugin = createActiveRecordPlugin(druidPlugin);
        activeRecordPlugin.addMapping("TEST_USER", User.class);
        plugins.add(activeRecordPlugin);
    }

    private DruidPlugin createDruidPlugin() {
        DruidPlugin druidPlugin = new DruidPlugin(
                PropKit.get("db.app.url"),
                PropKit.get("db.app.user"),
                PropKit.get("db.app.password"),
                PropKit.get("db.app.driver")
        );

        druidPlugin.addFilter(new StatFilter());
        WallFilter wallFilter = new WallFilter();
        wallFilter.setDbType(JdbcConstants.OCEANBASE);
        druidPlugin.addFilter(wallFilter);

        druidPlugin.setInitialSize(PropKit.getInt("db.app.poolInitialSize"));
        druidPlugin.setMaxPoolPreparedStatementPerConnectionSize(PropKit.getInt("db.app.poolMaxSize"));
        druidPlugin.setTimeBetweenConnectErrorMillis(PropKit.getInt("db.app.connectionTimeoutMillis"));
        druidPlugin.setValidationQuery("select 1 from dual");

        return druidPlugin;
    }

    private ActiveRecordPlugin createActiveRecordPlugin(DruidPlugin druidPlugin) {
        ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(druidPlugin);
        activeRecordPlugin.setDialect(new OracleDialect());

        return activeRecordPlugin;
    }

    public void init() {
        ActiveRecordPlugin arp = initDbConnection();
        boolean tableExists = Db.queryInt("SELECT COUNT(*) FROM USER_TABLES WHERE TABLE_NAME = 'TEST_USER'") > 0;
        if (!tableExists) {
            String sql = "CREATE TABLE TEST_USER (ID NUMBER(10), NAME VARCHAR2(50))";
            Db.update(sql);
        }
        arp.stop();
    }

    private ActiveRecordPlugin initDbConnection() {
        DruidPlugin druidPlugin = createDruidPlugin();
        ActiveRecordPlugin activeRecordPlugin = createActiveRecordPlugin(druidPlugin);

        druidPlugin.start();
        activeRecordPlugin.start();

        return activeRecordPlugin;
    }

    @Override
    public void configInterceptor(Interceptors interceptors) {
    }

    @Override
    public void configHandler(Handlers handlers) {
    }
}
package com.oceanbase.testjfinal.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.oceanbase.testjfinal.pojo.User;

import java.util.List;

public class UserController extends Controller {
    public void getData(){

        try {

            // Insert data
            String insertDataSql = "INSERT INTO TEST_USER (ID, NAME) VALUES (?, ?)";
            Db.update(insertDataSql, 1, "John");
            Db.update(insertDataSql, 2, "Jane");
            // Query data
            List<User> users;
            users = User.dao.find("SELECT * FROM TEST_USER");
            renderJson(users);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
package com.oceanbase.testjfinal.pojo;

import com.jfinal.plugin.activerecord.Model;


    public class User extends Model<User> {
        public static final User dao = new User();

}

References

For more information about OceanBase Connector/J, see OceanBase JDBC driver.

Contact Us