This topic introduces how to build an application by using a Tomcat connection pool, OceanBase Connector/J, and OceanBase Database. It also covers the use of the application for fundamental database operations, including table creation, data insertion, data deletion, data updating, and data query.
Click to download the tomcat-mysql-client sample project Prerequisites
- You have installed OceanBase Database.
- You have installed Java Development Kit (JDK) 1.8 and Maven.
- You have installed IntelliJ IDEA.
Note
The tool used to run the sample code in this topic is IntelliJ IDEA 2021.3.2 (Community Edition). You can also choose a tool of your preference to run the sample code.
Procedure
Note
The steps outlined in this topic are for the Windows environment. If you are using a different operating system or compiler, the steps may vary slightly.
- Import the
tomcat-mysql-clientproject into IntelliJ IDEA. - Obtain the connection information of OceanBase Database.
- Modify the database connection information in the
tomcat-mysql-clientproject. - Set up the Tomcat runtime environment of the
tomcat-mysql-clientproject. - Run the
tomcat-mysql-clientproject.
Step 1: Import the tomcat-mysql-client project into IntelliJ IDEA
Start IntelliJ IDEA and choose File > Open....

In the Open File or Project window, select the project files and click OK to import the files.
IntelliJ IDEA automatically recognizes the files and displays the project's directory structure, file list, module list, dependency relationships, and other details in the Project window. The Project window is typically positioned on the left side of the IntelliJ IDEA interface and is generally open by default. If the Project window is closed, you can reopen it by choosing View > Tool Windows > Project in the menu bar or by using the shortcut Alt + 1.
Note
When you import a project using IntelliJ IDEA, it will automatically detect the pom.xml file in the project, download the required dependency libraries based on the described dependencies in the file, and add them to the project.
View the project.

Step 2: Obtain the connection information of OceanBase Database
Contact the deployment personnel or administrator of OceanBase Database to obtain the corresponding database connection string.
obclient -hxx.xx.xx.xx -P2883 -uroot@sys#cluster -p**** -AFill in the URL below based on the OceanBase Database that has been deployed.
Note
The URL is required in the
application.propertiesfile.jdbc:oceanbase://host:port/schema_name?user=$user_name&password=$password&characterEncoding=UTF-8Parameter description:
host: the IP address for connecting to OceanBase Database. For connection through ODP, use the IP address of an ODP. For direct connection, use the IP address of an OBServer node.port: the port for connecting to OceanBase Database. For connection through ODP, the default value is2883, which can be customized when ODP is deployed. For direct connection, the default value is2881, which can be customized when OceanBase Database is deployed.schema_name: the name of the schema to be accessed.user_name: the tenant account. For connection through ODP, the format isusername@tenant name#cluster nameorcluster name:tenant name:username. For direct connection, the format isusername@tenant name.password: the password of the account.characterEncoding: the character encoding supported by the database URL option. Default value:utf8.
For more information about URL parameters, see Database URL.
Step 3: Modify the database connection information in the tomcat-mysql-client project
Modify the database connection information in the application.properties file based on the information obtained in Step 2: Obtain the connection information of OceanBase Database.
Here is an example:
- The name of the database driver is:
com.oceanbase.jdbc.Driver. - The IP address of the OBServer node is
10.10.10.1. - The port is 2881.
- The name of the database to be accessed is
TEST. - The tenant account is
root@xymysql. Here,xymysqlrefers to a MySQL-mode user tenant that is created in OceanBase Database, androotis the username of thexymysqltenant. - The password is
******.
Sample code:
#Apache Commons DBCP2 Connection Pool
#Database Connection Pool Driver Class Name
db.app.pool.driverClassName=com.oceanbase.jdbc.Driver
#Database URL
db.app.pool.url=jdbc:oceanbase://10.10.10.1/TEST?characterEncoding=UTF-8
#Database username
db.app.pool.username=root@xymysqll
#Database password
db.app.pool.password=******
#Initial size of connection pool
db.app.pool.initialSize=3
#Maximum number of connections in the connection pool
db.app.pool.maxTotal=10
#Maximum number of idle connections in the connection pool
db.app.pool.maxIdle=20
#Minimum number of idle connections in the connection pool
db.app.pool.minIdle=5
#Maximum wait time for obtaining connections (in milliseconds)
db.app.pool.maxWaitMillis=5000
#Verify the connection's query statement
db.app.pool.validationQuery=select 1 from dual
Step 4: Set up the Tomcat runtime environment of the tomcat-mysql-client project
Download the Tomcat 8.5.95 package.
Download the Tomcat 8.5.95 package from the Apache Tomcat official website and decompress the package to the desired installation directory.
Configure Tomcat in IntelliJ IDEA.
- Open IntelliJ IDEA and choose File > Settings > Plugins. In the search box in the middle of the Settings window, search for Smart Tomcat, download it and click Apply. The Tomcat Server tab appears at the bottom of the left-side pane. Click it, and then click the + sign on the right to browse and select the decompressed Tomcat directory. Click Apply and then OK to complete the configuration.

Create a Tomcat run configuration.
In the top menu of IntelliJ IDEA, choose Run > Edit Configurations. In the left pane of the Run/Debug Configurations window, click the + sign and choose Tomcat Server. Enter a name for the server in the Name field. In the Configuration drop-down list, select Tomcat Sever corresponding to your installation version. Change the Context path to
/and the SSL port to8080. Next to Before launch, click + and select Launch Web Browser. Click Edit and enterhttp://localhost:8080/hello/getData. Click Apply and then OK to complete the configuration.
Start the Tomcat server.
In the top menu of IntelliJ IDEA, select the Tomcat run configuration that you created. Click the green triangle to start the Tomcat server. You can view the startup logs of the Tomcat server in the Run window of IntelliJ IDEA.
Step 5: Run the tomcat-mysql-client project
Determine the running path.
In the top toolbar of IDEA, select the Tomcat running configuration that you created. Click the green triangle to start the Tomcat server. In Google Chrome or Internet Explorer, open the
http://localhost:8080/hello/getDatapath to view the running result.View the running result.
In the console window of IDEA, view the log information and output results of the project.
Result after data is inserted.
tomcat connection pool test 0 tomcat connection pool test 1 tomcat connection pool test 2 tomcat connection pool test 3 tomcat connection pool test 4 tomcat connection pool test 5 tomcat connection pool test 6 tomcat connection pool test 7 tomcat connection pool test 8 tomcat connection pool test 9Result after data is modified.
-----Modified----- POOl connection pool test 0 POOl connection pool test 1 POOl connection pool test 2 POOl connection pool test 3 POOl connection pool test 4 POOl connection pool test 5 POOl connection pool test 6 POOl connection pool test 7 POOl connection pool test 8 POOl connection pool test 9Result returned to the web interface.

Project code introduction
Click tomcat-mysql-client to download the project code, which is a compressed package named tomcat-mysql-client.
After decompressing it, you will find a folder named tomcat-mysql-client. The directory structure is as follows:
│--pom.xml
│
├─.idea
│
├─src
│ ├─main
│ │ ├─java
│ │ │ └─com
│ │ │ └─oceanbase
│ │ │ └─testtomcat
│ │ │ ├─config
│ │ │ │ └─UserConfig.java
│ │ │ │
│ │ │ ├─controller
│ │ │ │ └─UserController.java
│ │ │ │
│ │ │ └─pojo
│ │ │ └─User.java
│ │ │
│ │ ├─resources
│ │ │ └─application.properties
│ │ │
│ │ └─webapp
│ │ └─WEB-INF
│ │ └─web.xml
│ │
│ │
│ │
│ └─test
│ └─java
│
│
└─target
File description:
pom.xml: the configuration file of the Maven project, which contains the dependencies, plugins, and build details of the project..idea: the directory used to store project-related configuration information in the Integrated Development Environment (IDE).src: a directory that usually indicates the project directory for storing source code.main: the directory for storing main source code and resource files.java: the directory for storing Java source code.com: the root directory for storing Java packages.oceanbase: the root directory for storing the project.testtomcat: the directory for storing JFinal framework-related code.config: the configuration file directory, containing the configuration class files of the application.UserConfig.java: the user configuration class file.controller: the controller directory, containing the controller class files of the application.UserController.java: the user controller class file.pojo: the directory for storing JavaBean or entity classes.User.java: the file for storing the user entity class.resources: the directory for storing resource files such as configuration files and SQL files.application.properties: the configuration file for storing database connection information.webapp: the directory for storing static resources and configuration files of the web application.WEB-INF: the directory for storing configuration files and other protected resource files of the web application.web.xml: the deployment descriptor file of the web application.test: the directory for storing test code and resource files.target: the directory for storing compiled class files, JAR packages, and other files.
pom.xml code
Note
If you just want to verify the sample, you can use the default code without modification. You can also modify the pom.xml file as needed based on the following introduction.
The content of the pom.xml configuration file is as follows:
Declaration statement.
Declare this file to be an XML file that uses XML standard
1.0and character encodingUTF-8.Sample code:
<?xml version="1.0" encoding="UTF-8"?>Configure namespaces and the POM model version.
- Use
xmlnsto set the POM namespace tohttp://maven.apache.org/POM/4.0.0. - Use
xmlns:xsito set the XML namespace tohttp://www.w3.org/2001/XMLSchema-instance. - Use
xsi:schemaLocationto set the POM namespace tohttp://maven.apache.org/POM/4.0.0, and the URI of the corresponding XSD file tohttp://maven.apache.org/xsd/maven-4.0.0.xsd. - Use the
<modelVersion>element to set the POM model version used by the POM file to4.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>- Use
Configure basic information.
- Use
<groupId>to specify the project identifier ascom.oceanbase. - Use
<artifactId>to specify the project dependency astomcat-mysql-client. - Use
<version>to specify the project version as1.0-SNAPSHOT. - Use
<packaging>to specify the project packaging type as WAR (Web Application Archive).
Sample code:
<groupId>com.oceanbase</groupId> <artifactId>tomcat-mysql-client</artifactId> <version>1.0-SNAPSHOT</version> <!-- Packaging method (default to jar) --> <packaging>war</packaging>- Use
Configure the Maven version.
Specify the source code version and target code version of the compiler to be Java 8 respectively through <maven.compiler.source> and <maven.compiler.target>.
Sample code:
<properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties>Configure core dependencies.
Specify the group, name, and version of the dependency as com.jfinal, jfinal, and 5.0.6 respectively. 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>Specify the group, name, and version of the dependency as
com.alibaba,druid, and1.2.8respectively. This dependency allows you to use the Druid library for managing and optimizing the acquisition and release of database connections.Sample code:
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency>Specify the group, name, and version of the dependency as
org.apache.commons,commons-dbcp2, and2.9.0respectively. This dependency allows you to use the Apache Commons DBCP2 library for managing and optimizing the acquisition and release of database connections.Sample code:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.9.0</version> </dependency>Specify the group, name, and version of the dependency as
mysql,mysql-connector-java, and5.1.40respectively. This dependency allows you to use the client features provided by OceanBase Database, such as connection, query, and transaction.Sample code:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency>
introduction to the application.properties file
The application.properties file configures the database connection information for connecting to OceanBase Database. It includes the class name of the database driver, the connection URL, the username, the password, and the connection pool configurations. These configurations are used to obtain and manage database connections in the application for database operations.
The
db.app.pool.driverClassNameparameter specifies the database driver ascom.mysql.jdbc.Driverto establish a connection with OceanBase Database.The
db.app.pool.urlparameter specifies the URL for connecting to the database.The
db.app.pool.usernameparameter specifies the username for connecting to the database.The
db.app.pool.passwordparameter specifies the password for connecting to the database.The
db.app.pool.initialSizeparameter specifies the initial size of the connection pool as3, indicating that 3 database connections are created initially.The
db.app.pool.maxTotalparameter specifies the maximum size of the connection pool as10, indicating that the connection pool can have at most 10 database connections.The
db.app.pool.maxIdleparameter specifies the maximum number of idle connections in the connection pool as20.The
db.app.pool.minIdleparameter specifies the minimum number of idle connections in the connection pool as5.The
db.app.pool.maxWaitMillisparameter specifies the timeout for database connections as5000ms. If a connection is not obtained within 5000 ms, a timeout exception is thrown.The
db.app.pool.validationQueryparameter specifies the SQL query statement for validating database connections asselect 1. This means that when a connection is obtained from the connection pool, this query statement is executed to validate the connection.Sample code:
#Apache Commons DBCP2 Connection Pool #Database Connection Pool Driver Class Name db.app.pool.driverClassName=com.mysql.jdbc.Driver #Database URL db.app.pool.url=jdbc:mysql:////host:port/schema_name?characterEncoding=UTF-8 #Database username db.app.pool.username=user_name #Database password db.app.pool.password=****** #Initial size of connection pool db.app.pool.initialSize=3 #Maximum number of connections in the connection pool db.app.pool.maxTotal=10 #Maximum number of idle connections in the connection pool db.app.pool.maxIdle=20 #Minimum number of idle connections in the connection pool db.app.pool.minIdle=5 #Maximum wait time for obtaining connections (in milliseconds) db.app.pool.maxWaitMillis=5000 #Verify the connection's query statement db.app.pool.validationQuery=select 1
Common configurations for the DBCP built into Tomcat:
Notice
The specific attribute (parameter) configurations depend on project requirements and database characteristics. We recommend that you adjust and configure the attributes accordingly.
Attribute |
Default value |
Description |
|---|---|---|
| username | N/A | The username for connecting to the database. |
| password | N/A | The password for connecting to the database. |
| url | N/A | The URL for connecting to the database. |
| driverClassName | N/A | The standard Java class name of the database driver. |
| connectionProperties | N/A | The connection properties sent to the JDBC driver when a new connection is established. The value is in the [propertyName=property;] format. |
| defaultAutoCommit | driver default | The default auto-commit status of connections created by the connection pool. If this attribute is not specified, the setAutoCommit method is not called. |
| defaultReadOnly | driver default | The default read-only status of connections created by the connection pool. If this attribute is not specified, the setReadOnly method is not called. |
| defaultTransactionIsolation | driver default | The default transaction isolation level of connections created by the connection pool. |
| defaultCatalog | N/A | The default catalog of connections created by the connection pool. |
| cacheState | true | Specifies whether to cache the readOnly and autoCommit settings of connections. If this attribute is set to True, the current readOnly and autoCommit settings are cached when a read or write operation is performed for the first time, or for all subsequent write operations. This eliminates the need for additional database queries when calling getter methods. |
| defaultQueryTimeout | null | The query timeout for statements that create connections in the connection pool. If this attribute is not null, the value of this Integer attribute determines the query timeout for statements that create connections in the pool; if this attribute is null, the driver default value is used. |
| enableAutoCommitOnReturn | true | Specifies whether to check and configure the auto-commit status of a connection before it is returned to the connection pool. |
| rollbackOnReturn | true | Specifies whether to roll back a connection before it is returned to the connection pool. The connection is not rolled back if it is read-only. If this attribute is set to True, a connection that is not read-only and whose auto-commit status is disabled is rolled back before it is returned to the connection pool. |
| initialSize | 0 | The number of connections created when the connection pool starts. |
| maxTotal | 8 | The maximum number of active connections allocated from the connection pool. |
| maxIdle | 8 | The maximum number of idle connections retained in the connection pool without being released. If this attribute is set to a negative number, it indicates that there is no limit. |
| minIdle | 0 | The minimum number of idle connections retained in the connection pool without being created. A value of 0 indicates that no connections are created. |
| maxWaitMillis | indefinitely | The maximum number of milliseconds the pool waits (when no connections are available) for a connection to be returned before throwing an exception. A value of -1 indicates that the pool waits indefinitely. |
| validationQuery | N/A | The SQL query statement for validating connections. If this attribute is specified, the SQL query statement must be an SQL SELECT statement that returns at least one row. If this attribute is not specified, the validity of connections is verified by calling the isValid method. |
| validationQueryTimeout | no timeout | The timeout period in seconds for connection validation queries. |
| testOnCreate | false | Specifies whether to verify the object after it is created. If the object cannot be verified, the attempt to borrow the object will fail. |
| testOnBorrow | true | Specifies whether to verify the object before it is borrowed from the connection pool. If the object cannot be verified, it is removed from the connection pool and another object is borrowed. |
| testOnReturn | false | Specifies whether to verify the object before it is returned to the connection pool. |
| testWhileIdle | false | Specifies whether to verify objects that are idle in the connection pool by the idle object evictor (if any). If an object cannot be verified, it is removed from the connection pool. |
| timeBetweenEvictionRunsMillis | -1 | The number of milliseconds the idle object evictor thread sleeps between runs. If this attribute is set to a non-positive value, the idle object evictor thread is not run. |
| numTestsPerEvictionRun | 3 | The number of objects to be verified during each run of the idle object evictor thread. |
| minEvictableIdleTimeMillis | 1000 * 60 * 30 | The minimum time in milliseconds that an object can be idle in the connection pool. |
| softMinEvictableIdleTimeMillis | -1 | The minimum time in milliseconds that a connection can be idle in the connection pool, including the constraint of MinIdle. |
| maxConnLifetimeMillis | -1 | The maximum lifetime of a connection in milliseconds. If a connection cannot be activated, passivated, or verified within this period, it cannot be activated or passivated again. A value of 0 or a negative number indicates that a connection has an infinite lifetime. |
| logExpiredConnections | true | Specifies whether to log connections that are closed by the pool because they have exceeded their maximum lifetime. A value of False specifies to disable logging of expired connection. |
| connectionInitSqls | null | The SQL statements to be executed when a physical connection is initialized for the first time. These statements are executed only when the configured connection factory creates connections. |
| lifo | true | Specifies whether the borrowObject method returns the most recently used connection in the pool. If this attribute is set to True, the borrowObject method returns the last in connection (if any are available) from the most recently used connections in the pool; if this attribute is set to False, connections are obtained from the idle instance pool according to the order in which they were returned to the pool (FIFO queue). |
| poolPreparedStatements | false | Specifies whether to enable the prepared statement pool. |
| maxOpenPreparedStatements | unlimited | The maximum number of open statements allocated from the connection pool. A negative value indicates no limit. |
| accessToUnderlyingConnectionAllowed | false | Specifies whether to allow access to the underlying connection. |
| removeAbandonedOnMaintenance | false | Specifies whether to delete abandoned connections during connection pool maintenance. If this attribute is set to True, abandoned connections are deleted during maintenance, which is when the eviction is completed, unless the timeBetweenEvictionRunsMillis attribute is set to a positive value to enable maintenance. |
| removeAbandonedOnBorrow | false | Specifies whether to delete abandoned connections when a connection is borrowed from the connection pool. If this attribute is set to True, abandoned connections are deleted every time a connection is borrowed from the pool, with the following additional requirements:
|
| removeAbandonedTimeout | 300 | The timeout period in seconds before an abandoned connection is deleted. |
| logAbandoned | false | Specifies whether to log stack traces of application code for abandoned connections. Logging abandoned statements and connections increases the overhead for opening each connection or executing a new statement. |
| abandonedUsageTracking | false | Specifies whether to log stack traces for abandoned connections. If this attribute is set to True, stack traces are logged for each method call on a pool connection, and the most recent stack trace is retained to help debug abandoned connections. Setting this attribute to True incurs a significant overhead. |
| fastFailValidation | false | Specifies whether to quickly fail the validation of a connection that throws a fatal SQLException. If this attribute is set to True, the request to disconnect the connection is immediately failed, and the isValid method of the driver or the execution of the validation query is not called. By default, the following SQL_STATE codes are considered fatal error signals:
|
| disconnectionSqlCodes | null | A comma-separated list of SQL_STATE codes that are considered fatal disconnect errors. This attribute takes effect only when the fastFailValidation attribute is set to True. |
| jmxName | N/A | The name under which the data source is registered as a JMX MBean. This name must conform to the JMX object name syntax. |
Introduction to web.xml
The web.xml file is used to configure filters for web applications.
The web.xml configuration file contains the following content:
Document declaration.
The file is an XML file that uses XML standard
1.0and character encodingUTF-8.Sample code:
<?xml version="1.0" encoding="UTF-8"?>Configure the XML namespace and the XML model version.
- Use
xmlns:xsito specify the XML namespace ashttp://www.w3.org/2001/XMLSchema-instance. - Use
xmlnsto specify the XML namespace ashttp://java.sun.com/xml/ns/javaee. - Use
xsi:schemaLocationto specify the XML namespace ashttp://java.sun.com/xml/ns/javaee, and the URI of the corresponding XSD file ashttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd. - Use
<id>and<version>to specify the ID of the web application asWebApp_IDand the version number as3.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">- Use
Configure the JFinal filter.
Configure a filter named
jfinalto use the JFinal framework in the web application. Specify the class of the filter ascom.jfinal.core.JFinalFilter. Use the initialization parameterconfigClassto specify the location of the configuration class of the JFinal framework ascom.oceanbase.testtomcat.config.UserConfig. The JFinal 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.testtomcat.config.UserConfig</param-value> </init-param> </filter>Configure mappings of the JFinal filter.
Apply the
jfinalfilter to all request paths, namely, to all requests in the application.Sample code:
<filter-mapping> <filter-name>jfinal</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Introduction to UserConfig.java
The UserConfig.java file is used to configure routing, plugins, database connections, and other related information for the application.
The code in the UserConfig.java file mainly includes the following sections:
Reference other classes and interfaces.
Declare that the current file contains the following interfaces and classes:
StatFilter: a class used to statistics the performance of database access.JdbcConstants: a class used to define constants for database types.WallFilter: a class used to prevent SQL injection attacks.PropKit: a class used to read configuration files.ActiveRecordPlugin: a class used to operate databases.Db: a class used to execute database operations.MysqlDialect: a class used to specify the dialect of the database.DruidPlugin: a class used to connect to databases.Engine: a class used to configure template engines.UserController: a class used to process user-related requests.User: a 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.MysqlDialect; import com.jfinal.plugin.druid.DruidPlugin; import com.jfinal.template.Engine; import com.oceanbase.testjfinal.controller.UserController; import com.oceanbase.testjfinal.pojo.User;Define the
UserConfigclass.You can rewrite the methods of the
JFinalConfigclass to configure constants, routing, plugins, and database connections.Define the
configConstantmethod.Use this method to configure constants for the JFinal framework. Use
PropKitto read the configuration from the configuration file.Sample code:
@Override public void configConstant(Constants constants) { PropKit.use("application.properties"); }Define the
configRoutemethod.Use this method to configure routing mappings. Use the
routes.addmethod to map the"/hello"path to the default access page of theUserControllerclass.Sample code:
@Override public void configRoute(Routes routes) { routes.add("/hello", UserController.class, "/"); }Define the
configEnginemethod.Use this method to configure the template engine.
Sample code:
@Override public void configEngine(Engine engine) { }Define the
configPluginmethod.Use this method to configure the plugins of the application. Call the
initmethod to initialize the database connection and table structure. Create theDruidPluginandActiveRecordPluginplugins and add them to thepluginslist. Call theaddMappingmethod of theactiveRecordPluginto add the mapping between the database table and the entity class. Map theTEST_USERtable to theUserclass.Sample code:
@Override public void configPlugin(Plugins plugins) { init(); DruidPlugin druidPlugin = createDruidPlugin(); plugins.add(druidPlugin); ActiveRecordPlugin activeRecordPlugin = createActiveRecordPlugin(druidPlugin); activeRecordPlugin.addMapping("TOMCAT_TEST", User.class); plugins.add(activeRecordPlugin); }Define the
createDruidPluginmethod.Use this method to create the
DruidPluginplugin and configure the related parameters, such as the connection pool size, SQL firewall, and connection error handling.Use the
getmethod ofPropKitto get the database connection-related attribute values from the configuration file. These attribute values include the URL, username, password, and driver class. Then create aDruidPluginobject and initialize it with the attribute values.Use the
addFiltermethod to add aStatFilterinstance to theDruidPlugin. This instance is used to statistics the database access performance. Create aWallFilterinstance and use thesetDbTypemethod to set the database type to OceanBase Database. Then add theWallFilterinstance to theDruidPlugin. This instance is used to filter SQL statements.Use the
setInitialSizemethod to set the connection pool size. Use thesetMaxPoolPreparedStatementPerConnectionSizemethod to set the maximum number of preprocessed statements for each connection pool. Use thesetTimeBetweenConnectErrorMillismethod to set the time interval between two connection errors. Use thesetValidationQuerymethod to set the connection verification query statement. Finally, return the createdDruidPlugininstance.Sample code:
private DruidPlugin createDruidPlugin() { DruidPlugin druidPlugin = new DruidPlugin( PropKit.get("db.app.pool.url"), PropKit.get("db.app.pool.username"), PropKit.get("db.app.pool.password"), PropKit.get("db.app.pool.driverClassName") ); druidPlugin.addFilter(new StatFilter()); WallFilter wallFilter = new WallFilter(); wallFilter.setDbType(JdbcConstants.OCEANBASE); druidPlugin.addFilter(wallFilter); druidPlugin.setInitialSize(PropKit.getInt("db.app.pool.initialSize")); druidPlugin.setMaxPoolPreparedStatementPerConnectionSize(PropKit.getInt("db.app.pool.maxTotal")); druidPlugin.setTimeBetweenConnectErrorMillis(PropKit.getInt("db.app.pool.maxWaitMillis")); druidPlugin.setValidationQuery("select 1"); return druidPlugin; }
Define the
initmethod.Use this method to initialize the database connection and create a database table. Call the
initDbConnectionmethod to initialize the database connection and return anActiveRecordPlugininstance. Then execute an SQL statement to check whether the user table namedTOMCAT_TESTexists. If theTOMCAT_TESTtable exists, execute the SQL statementDROP TABLE TOMCAT_TESTto delete the table. Then execute theCREATE TABLEstatement to create a database table namedTOMCAT_TEST. This table contains theIDandUSERNAMEfields. Finally, disconnect from theActiveRecordPluginand release the database connection.Sample code:
public void init() { ActiveRecordPlugin arp = initDbConnection(); // Check if table exists boolean tableExists = Db.queryInt("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'TEST' AND TABLE_NAME = 'TOMCAT_TEST'") > 0; // Drop table if it exists if (tableExists) { Db.update("DROP TABLE TOMCAT_TEST"); } // Create table String sql = "CREATE TABLE TOMCAT_TEST (ID int, USERNAME varchar(50))"; Db.update(sql); arp.stop(); }Define the
initDbConnectionmethod.Use this method to initialize the database connection. First, call the
createDruidPluginmethod to create aDruidPluginobject and assign it to thedruidPluginvariable. This method is responsible for creating and configuring theDruidPluginfor managing the database connection pool. Next, call thecreateActiveRecordPluginmethod to create anActiveRecordPluginobject and pass theDruidPluginobject as a parameter to this method. This method is responsible for creating and configuring theActiveRecordPluginfor managing database operations. Then call thedruidPlugin.startmethod to start theDruidPluginand initialize the database connection pool. Finally, call theactiveRecordPlugin.startmethod to start theActiveRecordPlugin. This method will initialize the related 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; }Define the
ConfigInterceptorandConfigHandlermethods.Use these methods to perform global configuration during system initialization.
Sample code:
@Override public void configInterceptor(Interceptors interceptors) { } @Override public void configHandler(Handlers handlers) { }
Introduction to UserController.java
The UserController.java file uses the getData method to insert data into the database, query data from the database, and return the query results in JSON format to the client. It uses the Db class provided by the JFinal framework for database operations and the custom User class for data mapping.
The code in the UserController.java file mainly includes the following parts:
Reference other classes and interfaces.
Declare that the current file contains the following interfaces and classes:
Controllerclass: handles requests and responses.Dbclass: performs database operations.Recordclass: performs database operations such as querying, inserting, updating, and deleting data.ArrayListclass: creates an empty list.Userclass: maps database tables.Listinterface: operates on query result sets.
Sample code:
import com.jfinal.core.Controller; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Record; import java.util.ArrayList; import java.util.List;Define the
UserControllerclass.This class provides a controller for the JFinal framework and uses the
getDatamethod to insert data into and query data from the database.Insert data. Create a list named
dataListthat contains 10Recordobjects. EachRecordobject has a uniqueIDandUSERNAMEfield value. Use theDb.batchSavemethod to save the records in thedataListlist to a database table namedTOMCAT_TEST.Sample code:
for (int i = 0; i < 10; i++) { Record record = new Record().set("ID", i).set("USERNAME", "Tomcat connection pool test" + i); dataList.add(record); } Db.batchSave("TOMCAT_TEST", dataList, dataList.size());Query data. Use the
Db.findmethod to execute an SQL query and store the results in theresultListlist. Use an enhancedforloop to traverse eachRecordobject in theresultListlist. Use thegetStrmethod to obtain the value of a specified field in aRecordobject and use theSystem.out.printlnmethod to print the value.Sample code:
List<Record> resultList = Db.find("SELECT * FROM TOMCAT_TEST"); for (Record result : resultList) { System.out.println(result.getStr("USERNAME")); }Modify data. Use a loop to perform 10 iterations, executing an update statement in each iteration. Use the
Db.updatemethod to update records in theTOMCAT_TESTtable based on specified conditions.Sample code:
for (int i = 0; i < 10; i++) { Db.update("UPDATE TOMCAT_TEST SET USERNAME = 'Connection pool test" + i + "' WHERE ID = " + i); }Query the modified data. Query the
TOMCAT_TESTtable and save the results inmodifiedList. Print the message-----After modification-----. TraversemodifiedListand print theUSERNAMEfield value of each record. Use therenderJsonmethod to render the response messageData retrieved successfullyin JSON format and return it to the client.Sample code:
List<Record> modifiedList = Db.find("SELECT * FROM TOMCAT_TEST"); System.out.println("-----After modification-----"); for (Record modified : modifiedList) { System.out.println(modified.getStr("USERNAME")); } renderJson("Data retrieved successfully");
Introduction to User.java
The User.java file is used to map database tables and Java objects.
The code in the User.java file mainly includes the following parts:
Reference the
Modelclass.Use the
Modelclass to map database tables and operate data.Define the
Userclass.The
Userclass inherits the methods provided in theModelclass for database operations.Sample code:
import com.jfinal.plugin.activerecord.Model; public class User extends Model<User> { public static final User dao = new User(); }
Complete code
<?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>tomcat-mysql-client</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>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
</dependencies>
</project>
#Apache Commons DBCP2 Connection Pool
#Database Connection Pool Driver Class Name
db.app.pool.driverClassName=com.mysql.jdbc.Driver
#Database URL
db.app.pool.url=jdbc:mysql:////host:port/schema_name?characterEncoding=UTF-8
#Database username
db.app.pool.username=user_name
#Database password
db.app.pool.password=******
#Initial size of connection pool
db.app.pool.initialSize=3
#Maximum number of connections in the connection pool
db.app.pool.maxTotal=10
#Maximum number of idle connections in the connection pool
db.app.pool.maxIdle=20
#Minimum number of idle connections in the connection pool
db.app.pool.minIdle=5
#Maximum wait time for obtaining connections (in milliseconds)
db.app.pool.maxWaitMillis=5000
#Verify the connection's query statement
db.app.pool.validationQuery=select 1
<?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.testtomcat.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.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.Engine;
import com.oceanbase.testtomcat.controller.UserController;
import com.oceanbase.testtomcat.pojo.User;
public class UserConfig extends JFinalConfig {
@Override
public void configConstant(Constants constants) {
// Read properties configuration
PropKit.use("application.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("TOMCAT_TEST", User.class);
plugins.add(activeRecordPlugin);
}
private DruidPlugin createDruidPlugin() {
DruidPlugin druidPlugin = new DruidPlugin(
PropKit.get("db.app.pool.url"),
PropKit.get("db.app.pool.username"),
PropKit.get("db.app.pool.password"),
PropKit.get("db.app.pool.driverClassName")
);
druidPlugin.addFilter(new StatFilter());
WallFilter wallFilter = new WallFilter();
wallFilter.setDbType(JdbcConstants.OCEANBASE);
druidPlugin.addFilter(wallFilter);
druidPlugin.setInitialSize(PropKit.getInt("db.app.pool.initialSize"));
druidPlugin.setMaxPoolPreparedStatementPerConnectionSize(PropKit.getInt("db.app.pool.maxTotal"));
druidPlugin.setTimeBetweenConnectErrorMillis(PropKit.getInt("db.app.pool.maxWaitMillis"));
druidPlugin.setValidationQuery("select 1 from dual");
return druidPlugin;
}
private ActiveRecordPlugin createActiveRecordPlugin(DruidPlugin druidPlugin) {
ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(druidPlugin);
activeRecordPlugin.setDialect(new MysqlDialect());
return activeRecordPlugin;
}
public void init() {
ActiveRecordPlugin arp = initDbConnection();
// Check if table exists
boolean tableExists = Db.queryInt("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'TEST' AND TABLE_NAME = 'TOMCAT_TEST'") > 0;
// Drop table if it exists
if (tableExists) {
Db.update("DROP TABLE TOMCAT_TEST");
}
// Create table
String sql = "CREATE TABLE TOMCAT_TEST (ID int, USERNAME varchar(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.testtomcat.controller;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.util.ArrayList;
import java.util.List;
public class UserController extends Controller {
public void getData() {
try {
List<Record> dataList = new ArrayList<>();
// Insert data
for (int i = 0; i < 10; i++) {
Record record = new Record().set("ID", i).set("USERNAME", "Tomcat connection pool test" + i);
dataList.add(record);
}
Db.batchSave("TOMCAT_TEST", dataList, dataList.size());
// Query data
List<Record> resultList = Db.find("SELECT * FROM TOMCAT_TEST");
for (Record result : resultList) {
System.out.println(result.getStr("USERNAME"));
}
// Modify data
for (int i = 0; i < 10; i++) {
Db.update("UPDATE TOMCAT_TEST SET USERNAME = 'Connection pool test" + i + "' WHERE ID = " + i);
}
// Query modified data
List<Record> modifiedList = Db.find("SELECT * FROM TOMCAT_TEST");
System.out.println("-----Modified-----");
for (Record modified : modifiedList) {
System.out.println(modified.getStr("USERNAME"));
}
renderJson("Data retrieved successfully");
} catch (Exception e) {
e.printStackTrace();
renderJson("Error occurred");
}
}
}
package com.oceanbase.testtomcat.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 Connector/J.
