OceanBase logo

OceanBase

A unified distributed database ready for your transactional, analytical, and AI workloads.

DEPLOY YOUR WAY

OceanBase Cloud

The best way to deploy and scale OceanBase

OceanBase Enterprise

Run and manage OceanBase on your infra

TRY OPEN SOURCE

OceanBase Community Edition

The free, open-source distributed database

OceanBase seekdb

Open source AI native search database

Customer Stories

Real-world success stories from enterprises across diverse industries.

View All
BY USE CASES

Mission-Critical Transactions

Global & Multicloud Application

Elastic Scaling for Peak Traffic

Real-time Analytics

Active Geo-redundancy

Database Consolidation

Resources

Comprehensive knowledge hub for OceanBase.

Blog

Live Demos

Training & Certification

Documentation

Official technical guides, tutorials, API references, and manuals for all OceanBase products.

View All
PRODUCTS

OceanBase Cloud

OceanBase Database

Tools

Connectors and Middleware

QUICK START

OceanBase Cloud

OceanBase Database

BEST PRACTICES

Practical guides for utilizing OceanBase more effectively and conveniently

Company

Learn more about OceanBase – our company, partnerships, and trust and security initiatives.

About OceanBase

Partner

Trust Center

Contact Us

International - English
中国站 - 简体中文
日本 - 日本語
Sign In
Start on Cloud

A unified distributed database ready for your transactional, analytical, and AI workloads.

DEPLOY YOUR WAY

OceanBase Cloud

The best way to deploy and scale OceanBase

OceanBase Enterprise

Run and manage OceanBase on your infra

TRY OPEN SOURCE

OceanBase Community Edition

The free, open-source distributed database

OceanBase seekdb

Open source AI native search database

Customer Stories

Real-world success stories from enterprises across diverse industries.

View All
BY USE CASES

Mission-Critical Transactions

Global & Multicloud Application

Elastic Scaling for Peak Traffic

Real-time Analytics

Active Geo-redundancy

Database Consolidation

Comprehensive knowledge hub for OceanBase.

Blog

Live Demos

Training & Certification

Documentation

Official technical guides, tutorials, API references, and manuals for all OceanBase products.

View All
PRODUCTS
OceanBase CloudOceanBase Database
ToolsConnectors and Middleware
QUICK START
OceanBase CloudOceanBase Database
BEST PRACTICES

Practical guides for utilizing OceanBase more effectively and conveniently

Learn more about OceanBase – our company, partnerships, and trust and security initiatives.

About OceanBase

Partner

Trust Center

Contact Us

Start on Cloud
编组
All Products
    • Databases
    • iconOceanBase Database
    • iconOceanBase Cloud
    • iconOceanBase Tugraph
    • iconInteractive Tutorials
    • iconOceanBase Best Practices
    • Tools
    • iconOceanBase Cloud Platform
    • iconOceanBase Migration Service
    • iconOceanBase Developer Center
    • iconOceanBase Migration Assessment
    • iconOceanBase Admin Tool
    • iconOceanBase Loader and Dumper
    • iconOceanBase Deployer
    • iconKubernetes operator for OceanBase
    • iconOceanBase Diagnostic Tool
    • iconOceanBase Binlog Service
    • Connectors and Middleware
    • iconOceanBase Database Proxy
    • iconEmbedded SQL in C for OceanBase
    • iconOceanBase Call Interface
    • iconOceanBase Connector/C
    • iconOceanBase Connector/J
    • iconOceanBase Connector/ODBC
    • iconOceanBase Connector/NET
icon

OceanBase Cloud

  • Product Updates & Announcements
    • What's new
      • Release notes for 2026
      • Release notes for 2025
      • Release notes for 2024
      • Release history
    • Product announcements
      • Data development module deprecation notice
      • Optimization of Backup and Restore commercialization strategy
      • Cross-AZ data transfer billing (OceanBase Cloud on AWS)
      • Database Proxy pricing update
      • AWS instance pricing adjustment
  • Product Introduction
    • Overview
    • Management mode and scenarios
    • Core features
      • High availability with cross-cloud active-active architecture
      • High availability with cross-cloud primary-standby databases
      • Multi-level caching in shared storage
      • Multi-layer online scaling and on-demand adjustment
    • Deployment modes
    • Storage architecture
    • Product specifications
    • Product billing
      • Overview
      • Instance billing
        • Tencent Cloud instance billing
        • Alibaba Cloud instance billing
        • Huawei Cloud instance billing
        • AWS instance billing
        • GCP instance billing
      • Backup and restore billing
      • SQL audit billing
      • Migrations billing
      • Database proxy billing
      • Binlog service billing
      • Overview of OceanBase Cloud support plans
      • Read-only replica billing
    • Supported database versions
  • Get Started
    • Get started with a transactional instance
    • Get started with an analytical instance
    • Get started with a Key-Value instance
  • Work with Transactional Instances
    • Overview
    • Create an instance
      • Overview
      • Create via OceanBase Cloud official website
      • Create via AWS Marketplace
      • Create via GCP Marketplace
      • Create via Huawei Cloud Marketplace
      • Create via Alibaba Cloud Marketplace
      • Create via Azure Marketplace
    • Connect to an instance
      • MySQL compatible mode
        • Overview
        • Get connection string
          • Overview
          • Connect using AWS PrivateLink
          • Connect using Azure Private Link
          • Connect using Google Cloud Private Service Connect
          • Connect using Huawei Cloud VPC Endpoint
          • Connect using Alibaba Cloud VPC
          • Connect using a public IP address
          • Connect using a Huawei Cloud peering connection
        • Connect with clients
          • Connect to OceanBase Cloud by using Client ODC
          • Connect to OceanBase Cloud by using a MySQL client
          • Connect to OceanBase Cloud by using OBClient
        • Connect with drivers
          • Java
            • Connect to OceanBase Cloud using SpringBoot
            • SpringBatch sample application for connecting to OceanBase Cloud
            • spring-jdbc
            • SpringDataJPA sample application for connecting to OceanBase Cloud
            • Hibernate application development with OceanBase Cloud
            • Sample program for connecting to OceanBase Cloud
            • connector-j
            • Use TestContainers to connect to and use OceanBase Cloud
          • Python
            • Connect to OceanBase Cloud using mysqlclient
            • Connect to OceanBase Cloud using PyMySQL
            • Use the MySQL-connector-python driver to connect to and use OceanBase Cloud
            • Use SQLAlchemy to connect to an OceanBase Cloud database
            • Connect to an OceanBase Cloud database using Django
            • Connect to an OceanBase Cloud database by using peewee
          • C
            • Use MySQL Connector/C to connect to OceanBase Cloud
          • Go
            • Connect to OceanBase Cloud using the Go-SQL-Driver/MySQL driver
            • Connect to OceanBase Cloud using GORM
          • PHP
            • Use the EXT driver to connect to OceanBase Cloud
            • Connect to OceanBase Cloud by using the MySQLi driver
            • Use the PDO driver to connect to OceanBase Cloud
          • Rust
            • Rust application example for connecting to OceanBase Cloud
            • SeaORM example for connecting to OceanBase Cloud
          • ruby
            • ActiveRecord sample application for OceanBase Cloud
            • Connect to OceanBase Cloud by using mysql2
            • Connect to OceanBase Cloud by using Sequel
        • Use database connection pool
          • Database connection pool configuration
          • Connect to OceanBase Cloud by using a Tomcat connection pool
          • Connect to OceanBase Cloud by using a C3P0 connection pool
          • Connect to OceanBase Cloud by using a Proxool connection pool
          • Connect to OceanBase Cloud by using a HikariCP connection pool
          • Connect to OceanBase Cloud by using a DBCP connection pool
          • Connect to OceanBase Cloud by using Commons Pool
          • Connect to OceanBase Cloud by using a Druid connection pool
      • Oracle compatible mode
        • Overview
        • Get connection string
          • Overview
          • Connect using AWS PrivateLink
          • Connect using Azure Private Link
          • Connect using Google Cloud Private Service Connect
          • Connect using Huawei Cloud VPC Endpoint
          • Connect using a public IP address
        • Connect with clients
          • Connect to OceanBase Cloud by using OBClient
          • Connect to OceanBase Cloud by using Client ODC
        • Connect with drivers
          • Java
            • Connect to OceanBase Cloud using OceanBase Connector/J
            • Connect to OceanBase Cloud by using Spring Boot
            • SpringBatch application example for connecting to OceanBase Cloud
            • Connect to OceanBase Cloud using Spring JDBC
            • Connect to OceanBase Cloud by using Spring Data JPA
            • Connect to OceanBase Cloud by using Hibernate
            • Use MyBatis to connect to OceanBase Cloud
            • Use JFinal to connect to OceanBase Cloud
          • Python
            • Python Driver for Oracle Mode
          • C
            • Connect to OceanBase Cloud using OceanBase Connector/C
            • Connect to OceanBase Cloud using OceanBase Connector/ODBC
            • Use SqlSugar to connect to OceanBase Cloud
        • Use database connection pool
          • Database connection pool configuration
          • Sample program that uses a Tomcat connection pool to connect to OceanBase Cloud
          • C3P0 connection pool connects to OceanBase Cloud
          • Connect to OceanBase Cloud using Proxool connection pool
          • Sample program that uses HikariCP to connect to OceanBase Cloud
          • Use DBCP connection pool to connect to OceanBase Cloud
          • Connect to OceanBase Cloud by using Commons Pool
          • Connect to OceanBase Cloud by using a Druid connection pool
    • Developer guide
      • MySQL compatible mode
        • Plan database objects
          • Create a database
          • Create a table group
          • Create a table
          • Create an index
          • Create an external table
        • Write data
          • Insert data
          • Update data
          • Delete data
          • Replace data
          • Generate test data in batches
        • Read data
          • Single-table queries
          • Join tables
            • INNER JOIN queries
            • FULL JOIN queries
            • LEFT JOIN queries
            • RIGHT JOIN queries
            • Subqueries
            • Lateral derived tables
          • Use operators and functions in queries
            • Use arithmetic operators in queries
            • Use numerical functions in queries
            • Use string concatenation operators in queries
            • Use string functions in queries
            • Use datetime functions in queries
            • Use type conversion functions in queries
            • Use aggregate functions in queries
            • Use NULL-related functions in queries
            • Use the CASE conditional operator in queries
            • Use the SELECT ... FOR UPDATE statement to lock query results
            • Use the SELECT ... LOCK IN SHARE MODE statement to lock query results
          • Use a DBLink in queries
          • Set operations
        • Manage transactions
          • Overview
          • Start a transaction
          • Savepoints
            • Mark a savepoint
            • Roll back a transaction to a savepoint
            • Release a savepoint
          • Commit a transaction
          • Roll back a transaction
      • Oracle compatible mode
        • Plan database objects
          • Create a table group
          • Create a table
          • Create an index
          • Create an external table
        • Write data
          • Insert data
          • Update data
          • Delete data
          • Replace data
          • Generate test data in batches
        • Read data
          • Single-table queries
          • Join tables
            • INNER JOIN queries
            • FULL JOIN queries
            • LEFT JOIN queries
            • RIGHT JOIN queries
            • Subqueries
            • Lateral derived tables
          • Use operators and functions in queries
            • Use arithmetic operators in queries
            • Use numerical functions in queries
            • Use string concatenation operators in queries
            • Use string functions in queries
            • Use datetime functions in queries
            • Use type conversion functions in queries
            • Use aggregate functions in queries
            • Use NULL-related functions in queries
            • Use CASE functions in queries
            • Use the SELECT ... FOR UPDATE statement to lock query results
          • Use a DBLink in queries
          • Set operations
        • Manage transactions
          • Overview
          • Start a transaction
          • Savepoints
            • Mark a savepoint
            • Roll back a transaction to a savepoint
          • Commit a transaction
          • Roll back a transaction
    • Manage instances
      • Manage instances
        • View the instance list
        • Instance overview
        • Stop and restart instances
        • Unit migration
      • Manage tenants
        • Tenant overview
        • Create a tenant
        • Modify tenant specifications
        • Modify tenant names
        • Add an endpoint
        • Resource isolation
          • Overview
          • Manage resource groups
            • Create a resource group
            • View a resource group
            • Edit a resource group
            • Delete a resource group
          • Manage isolation rules
            • Create an isolation rule
            • View isolation rules
            • Edit an isolation rule
            • Delete a quarantine rule
        • Modify primary zone
        • Modify the maximum number of connections for a tenant proxy
        • Monitor tenant performance
          • Overview
          • View performance and SQL monitoring details
          • View transaction monitoring details
          • View storage and cache monitoring details
          • View Binlog service monitoring
          • Customize a monitoring dashboard for a tenant
        • Diagnostics
          • Real-time diagnostics
            • SQL diagnostics
              • Top SQL
              • Slow SQL
              • Suspicious SQL
              • High-risk SQL
            • SQL audit
        • Manage tenant parameters
          • Manage tenant parameters
          • Parameters for tenants
          • Parameter template overview
        • Delete a tenant
        • Manage databases and accounts
          • Create accounts
          • Manage accounts
          • Create a database (MySQL compatible mode)
          • Manage databases (MySQL compatible mode)
      • Monitor instance performance
        • Overview
        • Monitor the performance of databases in an instance
        • Monitor multidimensional metrics of an instance
        • Monitor the performance of hosts in an instance
        • Monitor database proxy
        • Monitor database proxy hosts
        • Monitor cross-cloud network performance
        • Customize a monitoring dashboard for an instance
      • Manage major compactions
        • Initiate a major compaction
        • View compaction records
        • Update time for compactions
      • Manage instance parameters
        • Manage parameters
        • Parameters for cluster instances
      • Change instance configurations
        • Enable storage auto-scaling
        • View history of configuration changes
        • Change configuration
        • Change configuration temporarily
        • Switch the deployment mode
      • Manage standby instances
        • Overview
        • Create a standby instance
        • Create a cross-cloud standby instance
        • Create a standby instance for an Alibaba Cloud primary instance
        • View details of primary and standby instances
        • Configure global endpoint
        • Enable automatic forwarding for write requests of standby databases
        • Primary-standby instance switchover
        • Initiate failover
        • Detach a standby instance
        • Release a standby instance
      • Release an instance
      • Database proxy
        • Overview
        • Manage database proxy
        • Direct load
      • Manage alerts
        • Overview
        • Manage alert rules
          • Create an alert rule
          • View an alert rule
          • Edit an alert rule
          • Delete an alert rule
        • View alert history
        • Manage alert templates
          • Create an alert template
          • View an alert template
          • Edit an alert template
          • Copy an alert rule template
          • Delete an alert template
        • Manage muting rules
          • Create an alert muting rule
          • View an alert muting rule
          • Edit an alert muting rule
          • Delete an alert muting rule
        • Manage alert notification templates
          • Create an alert notification template
          • View an alert notification template
          • Edit an alert notification template
          • Copy an alert notification template
          • Delete an alert notification template
        • Manage alert contacts
          • Add an alert contact
          • Add an alert contact group
          • View an alert contact
          • Edit an alert contact
          • Delete an alert contact
          • Obtain a webhook URL
        • Monitoring metrics for alerts
      • Backup and restore
        • Overview
        • Backup strategy
        • Initiate a backup immediately
        • Data backup
        • Initiate a restore
        • Data restore
        • Restore data from the instance recycle bin
      • Diagnostics
        • View performance monitoring data
        • Capacity diagnostics
        • One-click diagnostics
          • Initiate one-click diagnostics
          • View one-click diagnostic report
            • Exceptions
            • Real-time diagnostics
            • Optimization suggestions
            • Capacity management
            • Security management
        • Real-time diagnostics
          • SQL diagnostics
            • Top SQL
            • Slow SQL
            • Suspicious SQL
            • High-risk SQL
            • SQL details
            • SQL monitoring metrics list
          • Session management
            • Session management
          • Request analysis
            • Request analysis
        • Root cause diagnostics
          • Exception handling
          • Enable system autonomy
        • SQL audit
        • Materialized view analysis
        • Optimization center
          • Optimization suggestions
          • Manage active outlines
          • SQL review
          • View the optimization history
      • Manage tags
      • Manage read-only replicas
        • Overview
        • Instance read-only replicas
          • Add a read-only replica to an instance
          • View read-only replicas of an instance
          • Manage read-only replicas of an instance
          • Delete a read-only replica of an instance
        • Tenant read-only replicas
          • Add a read-only replica to a tenant
          • View read-only replicas of a tenant
          • Manage read-only replicas of a tenant
          • Delete a read-only replica of a tenant
      • Manage JVM-dependent services
    • Data source management
      • Create a data source
      • Manage data sources
      • User privileges
        • User privileges for compatibility assessment
        • User privileges for data migration
        • User privileges for performance assessment
        • User privileges for data archiving
        • User privileges for data cleanup
      • Connect via private network
        • AWS
        • Huawei Cloud
        • Alibaba Cloud
        • Google Cloud
        • Azure
        • Private IP address segments
      • Connect via public network
        • AWS
        • Huawei Cloud
        • Alibaba Cloud
        • Google Cloud
        • Azure
    • Data lifecycle management
      • Archive data
      • Clean up data
    • Manage recycle Bin
      • Instance recycle bin
      • Manage databases and tables in recycle bin
        • Overview
        • Instance-level recycle bin
        • Tenant-level recycle bin
  • Work with Analytical Instances
    • Overview
    • Core features
    • Create an instance
    • Connect to an instance
      • Overview
      • Get connection string
        • Overview
        • Connect using AWS PrivateLink
        • Connect using a public IP address
      • Connect with clients
        • Connect to OceanBase Cloud by using Client ODC
        • Connect to OceanBase Cloud by using a MySQL client
        • Connect to OceanBase Cloud by using OBClient
      • Connect with drivers
        • Java
          • Connect to OceanBase Cloud by using Spring Boot
          • Connect to OceanBase Cloud by using Spring Batch
          • Connect to OceanBase Cloud by using Spring Data JDBC
          • Connect to OceanBase Cloud by using Spring Data JPA
          • Connect to OceanBase Cloud by using Hibernate
          • Connect to OceanBase Cloud by using MyBatis
          • Connect to OceanBase Cloud using MySQL Connector/J
        • Python
          • Connect to OceanBase Cloud by using mysqlclient
          • Connect to OceanBase Cloud by using PyMySQL
          • Connect to OceanBase Cloud using MySQL Connector/Python
        • C
          • Connect to OceanBase Cloud using MySQL Connector/C
        • Go
          • Connect to OceanBase Cloud using Go-SQL-Driver/MySQL
        • PHP
          • Connect to OceanBase Cloud using PHP
      • Use database connection pool
        • Database connection pool configuration
        • Connect to OceanBase Cloud by using a Tomcat connection pool
        • Connect to OceanBase Cloud by using a C3P0 connection pool
        • Connect to OceanBase Cloud by using a Proxool connection pool
        • Connect to OceanBase Cloud by using a HikariCP connection pool
        • Connect to OceanBase Cloud by using a DBCP connection pool
        • Connect to OceanBase Cloud by using Commons Pool
        • Connect to OceanBase Cloud by using a Druid connection pool
    • Data table design
      • Table overview
      • Best practices
        • Unit 1: Best practices for optimizing storage structures and query performance
        • Unit 2: Best practices for creating special indexes
    • Export data
    • OceanBase data processing
    • Query acceleration
      • Statistics
      • Materialized views for query acceleration
      • Select a query parallelism level
    • Manage instances
      • Instance overview
      • Change configuration
      • Modify primary zone
      • Manage parameters
      • Backup and restore
        • Backup overview
        • Backup strategies
        • Immediate backup
        • Data backup
        • Initiate restore
        • Data restore
      • Monitor instance performance
        • Overview
        • Monitor the performance of databases in an instance
        • Monitor the performance of hosts in an instance
      • Manage major compactions
        • Initiate a major compaction
        • View compaction records
        • Update time for compactions
      • Database proxy
        • Overview
        • Manage database proxy
        • Direct load
      • Manage alerts
        • Overview
        • Manage alert rules
          • Create an alert rule
          • View an alert rule
          • Edit an alert rule
          • Delete an alert rule
        • View alert history
        • Manage alert templates
          • Create an alert template
          • View an alert template
          • Edit an alert template
          • Copy an alert template
          • Delete an alert template
        • Manage muting rules
          • Create an alert muting rule
          • View an alert muting rule
          • Edit an alert muting rule
          • Delete an alert muting rule
        • Manage alert notification templates
          • Create an alert notification template
          • View an alert notification template
          • Edit an alert notification template
          • Copy an alert notification template
          • Delete an alert notification template
        • Manage alert contacts
          • Add an alert contact
          • Add an alert contact group
          • View an alert contact
          • Edit an alert contact
          • Delete an alert contact
          • Obtain a webhook URL
        • Monitoring metrics for alerts
      • Diagnostics
        • View performance monitoring data
        • Capacity diagnostics
        • Real-time diagnostics
          • SQL diagnostics
            • Top SQL
            • Slow SQL
            • Suspicious SQL
            • High-risk SQL
            • SQL details
            • SQL monitoring metrics list
          • Session management
            • Session management
          • Optimization management
            • Manage active outlines
            • View the optimization history
          • Request analysis
            • Request analysis
      • Stop and restart instances
      • Release instances
      • Manage databases and accounts
        • Create and manage accounts
        • Create a database
        • Manage databases
      • Manage tags
    • Data lifecycle management
      • Archive data
      • Clean up data
    • Performance diagnosis and tuning
      • Use the DBMS_XPLAN package for performance diagnostics
      • Use the GV$SQL_PLAN_MONITOR view for performance analysis
      • Views related to AP performance analysis
    • Performance testing
    • Product integration
    • Manage recycle Bin
      • View instance recycle bin
      • Manage databases and tables in recycle bin
        • Overview
        • Instance recycle bin
  • Work with Key-Value Instances
    • Try out Key-Value instances
      • Create an instance
      • Create a tenant
      • Create an account for a database user
      • OBKV HBase data operation examples
    • Use Table model
      • Create an instance
      • Manage instances
        • Manage instances
          • View the instance list
          • Instance overview
          • Stop and restart instances
          • Release an instance
        • Manage tenants
          • Create a tenant
          • Modify tenant specifications
          • Modify tenant names
          • Delete a tenant
          • Tenant overview
          • Resource isolation
            • Overview
            • Manage resource groups
              • Create a resource group
              • View a resource group
              • Edit a resource group
              • Delete a resource group
            • Manage isolation rules
              • Create an isolation rule
              • View isolation rules
              • Edit an isolation rule
              • Delete a quarantine rule
          • Monitor tenant performance
            • Overview
            • View performance and SQL monitoring details
            • View transaction monitoring details
            • View storage and cache monitoring details
            • OBKV-Table
            • Customize a monitoring dashboard for a tenant
          • Diagnostics
            • Top SQL
          • Manage tenant parameters
            • Manage tenant parameters
            • Parameters for tenants
          • Manage databases and accounts
            • Create and manage accounts
            • Create a database
            • Manage databases
          • Switch primary zone
        • Monitor instance performance
          • Overview
          • Monitor the performance of databases in an instance
          • Monitor multi-dimensional metrics of an instance
          • Monitor the performance of hosts in a cluster
          • Customize monitoring dashboards for an instance
        • Manage major compactions
          • Initiate major compactions
          • View compaction records
          • Update time for compactions
        • Manage instance parameters
          • Parameter management overview
          • Parameters for cluster instances
        • Change instance configurations
          • View history of configuration changes
          • Change configuration
          • Switch the deployment mode
        • Database proxy
          • Overview
          • Manage database proxy
        • Manage alerts
          • Overview
          • Manage alert rules
            • Create an alert rule
            • View an alert rule
            • Edit an alert rule
            • Delete an alert rule
          • View alert history
          • Manage alert templates
            • Create an alert template
            • View an alert template
            • Edit an alert template
            • Copy an alert template
            • Delete an alert template
          • Manage muting rules
            • Create an alert muting rule
            • View an alert muting rule
            • Edit an alert muting rule
            • Delete an alert muting rule
          • Manage alert contacts
            • Add an alert contact
            • Add an alert contact group
            • View an alert contact
            • Edit an alert contact
            • Delete an alert contact
            • Obtain a webhook URL
          • Monitoring metrics for alerts
        • Backup and restore
          • Backup overview
          • Backup strategies
          • Immediate backup
          • Data backup
          • Initiate restore
          • Data restore
        • Diagnostics
          • View performance monitoring data
          • Top SQL
          • Capacity diagnostics
          • Request analysis
        • Manage tags
        • Manage recycle Bin
          • View instance recycle bin
          • Manage databases and tables in recycle bin
            • Overview
            • Instance-level recycle bin
            • Tenant-level recycle bin
    • Use HBase model
      • OBKV-HBase Overview
      • Create an instance
      • Develop in HBase model
        • Connect to an instance by using the OBKV-HBase client
      • Manage instances
        • Manage instances
          • View the instance list
          • Instance overview
          • Stop and restart instances
          • Release an instance
        • Manage tenants
          • Create a tenant
          • Modify tenant specifications
          • Modify tenant names
          • Delete a tenant
          • Tenant overview
          • Resource isolation
            • Overview
            • Manage resource groups
              • Create a resource group
              • View a resource group
              • Edit a resource group
              • Delete a resource group
            • Manage isolation rules
              • Create an isolation rule
              • View isolation rules
              • Edit an isolation rule
              • Delete a quarantine rule
          • Monitor tenant performance
            • Overview
            • View performance and SQL monitoring details
            • View transaction monitoring details
            • View storage and cache monitoring details
            • OBKV-HBase
            • Customize a monitoring dashboard for a tenant
          • Diagnostics
            • Top SQL
          • Manage tenant parameters
            • Manage tenant parameters
            • Parameters for tenants
          • Manage databases and accounts
            • Create and manage accounts
            • Create a database
            • Manage databases
          • Switch primary zone
        • Monitor instance performance
          • Overview
          • Monitor the performance of databases in an instance
          • Monitor multi-dimensional metrics of an instance
          • Monitor the performance of hosts in a cluster
          • Customize monitoring dashboards for an instance
        • Manage major compactions
          • Initiate major compactions
          • View compaction records
          • Update time for compactions
        • Manage instance parameters
          • Parameter management overview
          • Parameters for cluster instances
        • Change instance configurations
          • View history of configuration changes
          • Change configuration
          • Switch the deployment mode
        • Database proxy
          • Overview
          • Manage database proxy
        • Manage alerts
          • Overview
          • Manage alert rules
            • Create an alert rule
            • View an alert rule
            • Edit an alert rule
            • Delete an alert rule
          • View alert history
          • Manage alert templates
            • Create an alert template
            • View an alert template
            • Edit an alert template
            • Copy an alert template
            • Delete an alert template
          • Manage muting rules
            • Create an alert muting rule
            • View an alert muting rule
            • Edit an alert muting rule
            • Delete an alert muting rule
          • Manage alert contacts
            • Add an alert contact
            • Add an alert contact group
            • View an alert contact
            • Edit an alert contact
            • Delete an alert contact
            • Obtain a webhook URL
          • Monitoring metrics for alerts
        • Backup and restore
          • Backup overview
          • Backup strategies
          • Immediate backup
          • Data backup
          • Initiate restore
          • Data restore
        • Diagnostics
          • View performance monitoring data
          • Top SQL
          • Capacity diagnostics
          • Request analysis
        • Manage tags
        • Manage recycle Bin
          • View instance recycle bin
          • Manage databases and tables in recycle bin
            • Overview
            • Instance-level recycle bin
            • Tenant-level recycle bin
      • Performance test
    • Connect Key-Value instances
      • Overview
      • Connect using a public IP address
  • Migrations
    • Data migration and import solutions
    • Data assessment and migration quick start
    • Assess compatibility
      • Overview
      • Perform online assessment
      • Perform offline assessment
      • Manage compatibility assessment tasks
        • View a compatibility assessment task
        • View and download a compatibility assessment report
        • Stop a compatibility assessment task
        • Delete a compatibility assessment task
      • Obtain files for upload
      • Configure PrivateLink
      • Add an IP address to an allowlist
    • Migrate data
      • Overview
      • Migrations specification
      • Purchase a data migration instance
      • Migrate data from a MySQL database to a MySQL-compatible tenant of OceanBase Database
      • Migrate data from a MySQL-compatible tenant of OceanBase Database to a MySQL database
      • Migrate data between OceanBase database tenants of the same compatibility mode
      • Migrate data between OceanBase database tenants of different compatibility modes
      • Migrate data from an Oracle database to an Oracle-compatible tenant of OceanBase Database
      • Migrate data from an Oracle-compatible tenant of OceanBase Database to an Oracle database
      • Configure a two-way synchronization task
      • Migrate data from an OceanBase database to a Kafka instance
      • Migrate data from a TiDB database to a MySQL-compatible tenant of OceanBase Database
      • Migrate incremental data from a MySQL-compatible tenant of OceanBase Database to a TiDB Database
      • Migrate data from a PostgreSQL database to an OceanBase database
      • Migrate incremental data from an OceanBase Database to a PostgreSQL database
      • Manage data migration tasks
        • View details of a data migration task
        • Rename a data migration task
        • View and modify migration objects
        • View and modify migration parameters
        • Configure alert monitoring
        • Manage data migration tasks by using tags
        • Start, stop, and resume a data migration task
        • Clone a data migration task
        • Terminate and release a data migration task
      • Features
        • Custom DML/DDL configurations
        • DDL synchronization scope
        • Use SQL conditions to filter data
        • Rename a migration object
        • Set an incremental synchronization timestamp
        • Instructions on schema migration
        • Configure and modify matching rules
        • Wildcard rules
        • Import migration objects
        • Download conflict data
        • Change a topic
        • Column filtering
        • Data formats
      • Authorize an Alibaba Cloud account
      • SQL statements for querying table objects
      • Online DDL tools
      • Create a trigger
      • Modify the log level of a self-managed PostgreSQL instance
      • Supported DDL statements for synchronization and their limitations
        • DDL synchronization from Aurora MySQL DB clusters to MySQL-compatible tenants of OceanBase Database
        • DDL synchronization from MySQL-compatible tenants of OceanBase Database to Aurora MySQL DB clusters
        • DDL synchronization between MySQL-compatible tenants of OceanBase Database
        • DDL synchronization from Oracle databases to Oracle-compatible tenants of OceanBase Database
        • DDL synchronization from Oracle-compatible tenants of OceanBase Database to Oracle databases
        • DDL synchronization between Oracle-compatible tenants of OceanBase Database
        • DDL synchronization from OceanBase databases to Kafka instances
    • Data subscription
      • Create a data subscription task
      • Manage data subscription tasks
        • View details of a data subscription task
        • Configure subscription information
        • Modify the name of a data subscription task
        • View and modify subscription objects
        • View data subscription parameters
        • Set up data subscription alerts
        • Start, stop, and resume data subscription tasks
        • Clone a data subscription task
        • Release a data subscription task
      • Manage private connections for data subscriptions
      • Configure consumer subscription
      • Message formats
    • Data validation
      • Overview
      • Create a data validation task
      • Manage data validation tasks
        • View details of a data validation task
        • View and modify validation objects
        • View and modify validation parameters
        • Manage data validation tasks with tags
        • Start, pause, and resume data validation tasks
        • Clone a data validation task
        • Release a data validation task
      • Features
        • Import validation objects
        • Rename the validation object
        • Filter objects by using SQL conditions
        • Configure the matching rules for the validation object
    • Assess performance
      • Overview
      • Obtain traffic files from a database instance
      • Create a full performance assessment task
      • Create an SQL file parsing task
      • Create an SQL file replay task
      • Manage performance assessment tasks
        • View the details of a performance assessment task
        • View a performance assessment report
        • Retry and stop a performance assessment task
        • Delete a performance assessment task
      • Obtain a database instance
      • Create an access key
    • Import data
      • Import data
      • Direct load
      • Supported file formats and encoding formats for Data Import
      • Sample data introduction
    • Binlog service
      • Overview
      • Purchase the Binlog service
      • Manage Binlog Service
        • View details of the Binlog service
        • Change configuration
        • Modify the auto-scaling strategy for storage space
        • Modify the elasticity strategy for compute units
        • Disable the Binlog service
  • Security
    • OceanBase Cloud account settings
      • Modify login password
      • Multi-factor authentication
      • Manage AccessKeys
      • Time zone settings
      • Manage cloud marketplace accounts
      • Account audit
    • Organizations and projects
      • Overview
      • Manage organization information
      • Project management
        • Manage projects
        • Cross-project bidirectional authorization
        • Subscribe to project messages
      • Manage members
      • Permissions for roles
      • Cost management
        • Overview
        • Cost details
        • Manage cost units
      • Operation audit
    • Database accounts and privileges
      • Account privileges
      • Authorize cloud vendor accounts
      • AWS KMS key management
      • Support access control
    • Security and encryption
      • Set allowlist groups
      • SSL encryption
      • Transparent Data Encryption (TDE)
    • Monitoring dashboard
    • Events
  • SQL Console
    • Overview
    • Access SQL Console
    • SQL editing and execution
    • PL compilation
    • Result set editing
    • Execution analysis
    • Database object management
      • Create a table
      • Create a view
      • Create a function
      • Create a stored procedure
      • Create a program package
      • Create a trigger
      • Create a type
      • Create a sequence
      • Create a synonym
    • Session variable management
    • Functional keys in SQL Console
  • Integrations
    • Overview
    • Schema evolution
      • Liquibase
      • Flyway
    • Data ingestion
      • Canal
      • dbt
      • Debezium
      • Flink
      • Glue
      • Informatica Cloud
      • Kafka
      • Maxwell
      • SeaTunnel
      • DataWorks
      • NiFi
    • SQL development
      • DataGrip
      • DBeaver
      • Navicat
      • TablePlus
    • Orchestration
      • DolphinScheduler
      • Linkis
      • Airflow
    • Visualization
      • Grafana
      • Power BI
      • Quick BI
      • Superset
      • Tableau
    • Observability
      • Datadog
      • Prometheus
    • Database management
      • Bytebase
    • AI
      • LlamaIndex
      • Dify
      • LangChain
      • Tongyi Qianwen
      • OpenAI
      • n8n
      • Trae
      • SpringAI
      • Cline
      • Cursor
      • Continue
      • Toolbox
      • CamelAI
      • Firecrawl
      • Hugging Face
      • Ollama
      • Google Gemini
      • Cloudflare Workers AI
      • Jina AI
      • Augment Code
      • Claude Code
      • Kiro
    • Development tools
      • Cloudflare Workers
      • Vercel
  • Best practices
    • Best practices for achieving high availability through cross-cloud active-active deployment
    • High availability through cross-cloud primary-standby databases (1:1)
    • High availability through cross-cloud primary-standby databases (1:n)
    • High host CPU usage
    • Best practices for read/write splitting in OceanBase Cloud
  • References
    • System architecture
    • System management
    • Database object management
    • Database design and specification constraints
    • SQL reference
    • System views
    • Parameters and system variables
    • Error codes
    • Performance tuning
    • Open API References
      • Overview
      • Service endpoints
      • Using API
      • Open APIs
        • Cluster management
          • DescribeInstances
          • DescribeInstance
          • CreateInstance
          • DeleteInstance
          • ModifyInstanceName
          • describe-node-options
          • StopCluster
          • StartCluster
          • ModifyInstanceSpec
          • DescribeInstanceTopology
          • DescribeReadonlyInstances
          • CreateReadonlyInstance
          • ModifyReadonlyInstanceSpec
          • ModifyReadonlyInstanceDiskSize
          • ModifyReadonlyInstanceNodeNum
          • DeleteReadonlyInstance
          • DescribeInstanceAvailableRoZones
          • DescribeInstanceParameters
          • UpdateInstanceParameters
          • DescribeInstanceParametersHistory
          • ModifyInstanceTagList
          • ModifyInstanceNodeNum
        • Tenant management
          • DescribeTenants
          • DescribeTenant
          • CreateTenants
          • DeleteTenants
          • ModifyTenantName
          • ModifyTenant
          • ModifyTenantUserDescription
          • ModifyTenantUserStatus
          • GetTenantCreateConstraints
          • ModifyTenantPrimaryZone
          • GetTenantCreateCpuConstraints
          • GetTenantCreateMemConstraints
          • GetTenantModifyCpuConstraints
          • GetTenantModifyMemConstraints
          • CreateTenantSecurityIpGroup
          • DescribeTenantSecurityIpGroups
          • ModifyTenantSecurityIpGroup
          • DeleteTenantSecurityIpGroup
          • DescribeTenantPrivateLink
          • DeletePrivatelinkConnection
          • CreatePrivatelinkService
          • ConnectPrivatelinkService
          • AddPrivatelinkServiceUser
          • BatchKillProcessList
          • DescribeProcessStatsComposition
          • DescribeTenantAvailableRoZones
          • DescribeTenantAddressInfo
          • ModifyTenantReadonlyReplica
          • DescribeTenantParameters
          • UpdateTenantParameters
          • DescribeTenantParametersHistory
          • ModifyTenantTagList
        • Tenant user management
          • CreateTenantUser
          • DescribeTenantUsers
          • DeleteTenantUsers
          • ModifyTenantUserPassword
          • ModifyTenantUserRoles
        • Database management
          • CreateDatabase
          • DescribeDatabases
          • DeleteDatabases
          • ModifyDatabaseUserRoles
        • Backup and restore
          • DescribeDataBackupSet
          • DescribeRestorableTenants
          • ModifyBackupStrategy
          • CreateTenantRestoreTask
          • CreateDataBackupTask
          • DescribeOneDataBackupSet
        • Database proxy management
          • CreateTenantAddress
          • CreateTenantSingleTunnelSLBAddress
          • DeleteTenantAddress
          • DescribeTenantAddress
          • ModifyOdpClusterSpec
          • ModifyTenantAddressPort
          • ModifyTenantAddressDomainPrefix
          • ConfirmPrivatelinkConnection
          • DescribeTenantAddressInfo
        • Monitoring management
          • DescribeTenantMetrics
          • DescribeMetricsData
          • DescribeNodeMetrics
        • Diagnostic management
          • DescribeOasTopSQLList
          • DescribeOasAnomalySQLList
          • DescribeOasSlowSQLList
          • DescribeOasSQLText
          • DescribeSqlAudits
          • DescribeOutlineBinding
          • DescribeSampleSqlRawTexts
          • DescribeSQLTuningAdvices
          • DescribeOasSlowSQLSamples
          • DescribeOasSQLTrends
          • DescribeOasSQLPlanGroup
        • Security management
          • CreateSecurityIpGroup
          • DescribeInstanceSSL
          • ModifyInstanceSSL
          • DescribeTenantEncryption
          • ModifyTenantEncryption
          • ModifySecurityIps
          • DeleteSecurityIpGroup
          • DescribeTenantSecurityConfigs
          • DescribeInstanceSecurityConfigs
        • Tag management
          • DescribeTags
          • CreateTags
          • UpdateTag
          • DeleteTag
        • Historical event management
          • DescribeOperationEvents
      • Differences between ApsaraDB for OceanBase APIs and OceanBase Cloud APIs
    • Download OBClient
      • Download OBClient
      • Download OceanBase Connector/J
      • Download client ODC
      • Download OceanBase Connector/ODBC
      • Download OBClient Libs
    • Metrics References
      • Cluster database
      • Cluster hosts
      • Binlog service
      • Cross-cloud network channel connection
      • Performance and SQL
      • Transactions
      • Storage and caching
      • Proxy database
      • Proxy host
    • ODC User Guide
      • What is ODC?
        • What is ODC?
        • Limitations
      • Quick Start
        • Client ODC
          • Overview
          • Install Client ODC
          • Use Client ODC
        • Web ODC
          • Overview
          • Use Web ODC
      • Data Source Management
        • Create a data source
        • Data sources and project collaboration
        • Database O&M
          • Session management
          • Global variable management
          • Recycle bin management
      • SQL Development
        • Edit and execute SQL statements
        • Perform PL compilation and debugging
        • Edit and export the result set of an SQL statement
        • Execution analysis
        • Generate test data
        • System settings
        • Database objects
          • Table objects
            • Overview
            • Create a table
          • View objects
            • Overview
            • Create a view
            • Manage views
          • Materialized view objects
            • Overview
            • Create a materialized view
            • Manage materialized views
          • Function objects
            • Overview
            • Create a function
            • Manage functions
          • Stored procedure objects
            • Overview
            • Create a stored procedure
            • Manage stored procedures
          • Sequence objects
            • Overview
            • Create a sequence
            • Manage sequences
          • Package objects
            • Overview
            • Create a program package
            • Manage program packages
          • Trigger objects
            • Overview
            • Create a trigger
            • Manage triggers
          • Type objects
            • Overview
            • Create a type
            • Manage types
          • Synonym objects
            • Overview
            • Create a synonym
            • Manage synonyms
      • Import and Export
        • Import schemas and data
        • Export schemas and data
      • Database Change Management
        • User Permission Management
          • Users and roles
          • Automatic authorization
          • User permission management
        • Project collaboration management
        • Risk levels, risk identification rules, and approval processes
        • SQL check specifications
        • SQL window specification
        • Database change management
        • Batch database change management
        • Online schema changes
        • Synchronize shadow tables
        • Schema comparison
      • Data Lifecycle Management
        • Partitioning Plan Management
          • Manage partitioning plans
          • Set partitioning strategies
          • Examples
        • SQL plan task
      • Data Desensitization and Auditing
        • Desensitize data
        • Operation records
      • Notification Management
        • Overview
        • View notification records
        • Manage Notification Channel
          • Create a notification channel
          • View, edit, and delete a notification channel
          • Configure a custom channel
        • Manage notification rules
      • Best Practices
        • Tips for SQL development
        • Explore ODC team workspaces
        • Understanding real-time SQL diagnostics for OceanBase AP
        • OceanBase historical database solutions
        • ODC SQL check for automatic identification of high-risk operations
        • Manage and modify sharded databases and tables via ODC
        • Data masking and control practices
        • Enterprise-level control and collaboration: Safeguard every database change
    • Data Development
      • Overview
      • Workspace management
      • Worksheet management
      • Compute node pool management
      • Workflow management
      • Dashboard management
      • Manage Git repositories
      • SQL development
        • SQL editing and execution
        • Result set editing
        • Execution analysis
        • Database object management
          • Create a table
          • Create a view
          • Create a function
          • Create a stored procedure
        • Session variable management
        • Git integration
      • Sample datasets
      • Data development terms
  • Manage Billing
    • Access billing
    • View monthly bills
    • View payment details
    • View orders
    • Use vouchers for payment
    • View invoices
  • Legal Agreements
    • OceanBase Cloud Services Agreement
    • Service Level Agreement
    • OceanBase Data Processing Addendum
    • Service Level Agreement for OceanBase Cloud Migration Service

Download PDF

Release notes for 2026 Release notes for 2025 Release notes for 2024 Release history Data development module deprecation notice Optimization of Backup and Restore commercialization strategy Cross-AZ data transfer billing (OceanBase Cloud on AWS) Database Proxy pricing update AWS instance pricing adjustment Overview Management mode and scenarios High availability with cross-cloud active-active architecture High availability with cross-cloud primary-standby databases Multi-level caching in shared storage Multi-layer online scaling and on-demand adjustment Deployment modes Storage architecture Product specifications Overview Backup and restore billing SQL audit billing Migrations billing Database proxy billing Binlog service billing Overview of OceanBase Cloud support plans Read-only replica billing Supported database versions Get started with a transactional instance Get started with an analytical instance Get started with a Key-Value instance Overview Overview Create via OceanBase Cloud official website Create via AWS Marketplace Create via GCP Marketplace Create via Huawei Cloud Marketplace Create via Alibaba Cloud Marketplace Create via Azure Marketplace Release an instance Manage tags Manage JVM-dependent services Create a data source Manage data sources Archive data Clean up data Instance recycle bin Overview Core features Create an instance Overview Table overview Export data OceanBase data processing Statistics Materialized views for query acceleration Select a query parallelism level Instance overview Change configuration Modify primary zone Manage parameters Stop and restart instances Release instances Manage tags Archive data Clean up data Use the DBMS_XPLAN package for performance diagnostics Use the GV$SQL_PLAN_MONITOR view for performance analysis Views related to AP performance analysis Performance testing Product integration View instance recycle bin Create an instance Create a tenant Create an account for a database user OBKV HBase data operation examples Create an instance OBKV-HBase Overview Create an instance Performance test Overview Connect using a public IP address Data migration and import solutions Data assessment and migration quick start Overview Perform online assessment Perform offline assessment Obtain files for upload Configure PrivateLink Add an IP address to an allowlist Overview Migrations specification Purchase a data migration instance Migrate data from a MySQL database to a MySQL-compatible tenant of OceanBase Database Migrate data from a MySQL-compatible tenant of OceanBase Database to a MySQL database Migrate data between OceanBase database tenants of the same compatibility mode Migrate data between OceanBase database tenants of different compatibility modes Migrate data from an Oracle database to an Oracle-compatible tenant of OceanBase Database Migrate data from an Oracle-compatible tenant of OceanBase Database to an Oracle database Configure a two-way synchronization task Migrate data from an OceanBase database to a Kafka instance
OceanBase logo

The Unified Distributed Database for the AI Era.

Follow Us
Products
OceanBase CloudOceanBase EnterpriseOceanBase Community EditionOceanBase seekdb
Resources
DocsBlogLive DemosTraining & Certification
Company
About OceanBaseTrust CenterLegalPartnerContact Us
Follow Us

© OceanBase 2026. All rights reserved

Cloud Service AgreementPrivacy PolicySecurity
Contact Us
Document Feedback
  1. Documentation Center
  2. OceanBase Cloud
iconOceanBase Cloud

    Use MyBatis to connect to OceanBase Cloud

    Last Updated:2026-04-07 08:08:33  Updated
    share
    What is on this page
    Prerequisites
    Procedure
    Step 1: Obtain the connection string of the OceanBase Cloud database
    Step 2: Import the java-oceanbase-mybatis project into IntelliJ IDEA
    Step 3: Modify the database connection information in the java-oceanbase-mybatis project
    Step 4: Run the java-oceanbase-mybatis project
    Project code
    Introduction to the pom.xml file
    Introduction to the jdbc.properties file
    Overview of the mybatis-config.xml file
    Introduction to the code in the IUserMapper.xml file
    Introduction to the code in the IAppMapper.java file
    Introduction to the code in the IUserMapper.java file
    App.java code introduction
    User.java code introduction
    Overview of the MyBatisTest.java file
    Full code
    References

    folded

    share

    This topic describes how to build an application by using the MyBatis framework and OceanBase Cloud. The application can perform basic operations such as creating a table, inserting data, and querying data.

    Download the java-oceanbase-mybatis sample project Use MyBatis to connect to OceanBase Cloud (Oracle compatible mode)

    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 choose your preferred tool to run the code examples.

    Procedure

    Note

    The following procedure is 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 the OceanBase Cloud database.
    2. Import the java-oceanbase-mybatis project into IntelliJ IDEA.
    3. Modify the database connection information in the java-oceanbase-mybatis project.
    4. Run the java-oceanbase-mybatis 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 select Connect > Get Connection String under the target tenant.

      For more information, see Obtain the connection string.

    2. Fill in the corresponding information in the URL based on the created OceanBase Cloud database.

      Note

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

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

      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, which is 1521 by default.

      • $schema_name: the name of the schema to be accessed.

      • $user_name: the account for accessing the database.

      • $password: the password of the account.

      • useServerPrepStmts=true&rewriteBatchedStatements=true: additional connection attributes.

        • rewriteBatchedStatements: rewrites batchedStatement for insert queries to execute them in a single executeQuery. When rewriteBatchedStatements is active, the useServerPrepStmts option is set to false. Default value: false.
        • useServerPrepStmts: prepares PrepareStatement on the server side before execution. Enabling this parameter can reduce the number of times the same SQL statement is compiled and parsed in the database when the same SQL statement needs to be executed repeatedly by the application.

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

    Step 2: Import the java-oceanbase-mybatis project into IntelliJ IDEA

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

      file

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

    3. IntelliJ IDEA will automatically recognize various files in the project and display the project structure, file list, module list, and dependencies 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 the shortcut key Alt + 1 to reopen 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, and adds them to the project.

    4. View the project.

      testmybatis

    Step 3: Modify the database connection information in the java-oceanbase-mybatis project

    Modify the database connection information in the jdbc.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 access port is 1521.
    • The name of the schema to be accessed is sys.
    • The tenant connection account is oracle001.
    • The password is ******.

    Here is the sample code:

    jdbc.driver=com.oceanbase.jdbc.Driver
    jdbc.url=jdbc:oceanbase://t5******.********.oceanbase.cloud:1521/sys?useServerPrepStmts=true&rewriteBatchedStatements=true
    jdbc.username=oracle001
    jdbc.password=******
    

    Step 4: Run the java-oceanbase-mybatis project

    Running path

    1. In the project structure, locate the TestMybatis.java file in the src > test > java directory.
    2. In the toolbar, select Run(U) > Run > TestMybatis, or click the green triangle in the upper right corner to run it.
    3. View the log information and output results in the console of IntelliJ IDEA.

    Running result

    1. The output result of the testUserMapper method is as follows:

      User{id=2, name='update'}
      User{id=3, name='insert'}
      User{id=4, name='insert'}
      User{id=5, name='insert'}
      User{id=6, name='insert'}
      User{id=7, name='insert'}
      User{id=8, name='insert'}
      User{id=9, name='insert'}
      User{id=10, name='insert'}
      usersByPage = [User{id=5, name='insert'}, User{id=6, name='insert'}, User{id=7, name='insert'}]
      
    2. The output result of the testSqlSession method is as follows:

      User{id=2, name='update'}
      User{id=3, name='insert'}
      User{id=4, name='insert'}
      User{id=5, name='insert'}
      User{id=6, name='insert'}
      User{id=7, name='insert'}
      User{id=8, name='insert'}
      User{id=9, name='insert'}
      User{id=10, name='insert'}
      
    3. The output result of the testAppMapper method is as follows:

      App{id=2, name='update'}
      App{id=3, name='insert3'}
      App{id=4, name='insert4'}
      App{id=5, name='insert5'}
      App{id=6, name='insert6'}
      App{id=7, name='insert7'}
      App{id=8, name='insert8'}
      App{id=9, name='insert9'}
      App{id=10, name='insert10'}
      pageList = Page{count=true, pageNum=2, pageSize=3, startRow=3, endRow=6, total=9, pages=3, reasonable=false, pageSizeZero=true}[App{id=5, name='insert5'}, App{id=6, name='insert6'}, App{id=7, name='insert7'}]
      
    4. The complete output result is as follows:

      User{id=2, name='update'}
      User{id=3, name='insert'}
      User{id=4, name='insert'}
      User{id=5, name='insert'}
      User{id=6, name='insert'}
      User{id=7, name='insert'}
      User{id=8, name='insert'}
      User{id=9, name='insert'}
      User{id=10, name='insert'}
      usersByPage = [User{id=5, name='insert'}, User{id=6, name='insert'}, User{id=7, name='insert'}]
      App{id=2, name='update'}
      App{id=3, name='insert3'}
      App{id=4, name='insert4'}
      App{id=5, name='insert5'}
      App{id=6, name='insert6'}
      App{id=7, name='insert7'}
      App{id=8, name='insert8'}
      App{id=9, name='insert9'}
      App{id=10, name='insert10'}
      pageList = Page{count=true, pageNum=2, pageSize=3, startRow=3, endRow=6, total=9, pages=3, reasonable=false, pageSizeZero=true}[App{id=5, name='insert5'}, App{id=6, name='insert6'}, App{id=7, name='insert7'}]
      User{id=2, name='update'}
      User{id=3, name='insert'}
      User{id=4, name='insert'}
      User{id=5, name='insert'}
      User{id=6, name='insert'}
      User{id=7, name='insert'}
      User{id=8, name='insert'}
      User{id=9, name='insert'}
      User{id=10, name='insert'}
      

    Project code

    Click java-oceanbase-mybatis to download the project code. The file is a compressed package named java-oceanbase-mybatis.

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

    │--pom.xml
    │
    ├─.idea
    │
    ├─src
    │  ├─main
    │  │  ├─java
    │  │  │  └─com
    │  │  │      └─oceanbase
    │  │  │          ├─mapper
    │  │  │          │------IAppMapper.java
    │  │  │          │------IUserMapper.java
    │  │  │          │
    │  │  │          └─pojo
    │  │  │              │---App.java
    │  │  │              └─--User.java
    │  │  │
    │  │  └─resources
    │  │      │--jdbc.properties
    │  │      │--mybatis-config.xml
    │  │      │
    │  │      └─com
    │  │          └─oceanbase
    │  │              └─mapper
    │  │                  └─---IUserMapper.xml
    │  │
    │  └─test
    │      └─java
    │          └─---TestMybatis.java
    │
    └─target
    

    File description:

    • pom.xml: the configuration file of the Maven project, which contains information about the project's dependencies, plugins, and build process.
    • .idea: a directory used in the Integrated Development Environment (IDE) to store project-related configuration information.
    • src: a directory typically used to store the source code of the project.
    • main: a directory for storing the main source code and resource files.
    • java: a directory for storing Java source code.
    • com: the root directory for storing Java packages.
    • oceanbase: the root directory for storing the project.
    • mapper: a directory for storing MyBatis Mapper interfaces and XML files.
    • IAppMapper.java: a file for storing the application data access layer interface.
    • IUserMapper.java: a file for storing the user data access layer interface.
    • pojo: a directory for storing JavaBeans or entity classes.
    • App.java: a file for storing the application entity class.
    • User.java: a file for storing the user entity class.
    • resources: a directory for storing resource files, such as configuration files and SQL files.
    • jdbc.properties: a configuration file for storing database connection information.
    • mybatis-config.xml: a file for storing MyBatis configuration.
    • IUserMapper.xml: an XML file for storing the user data access layer configuration.
    • test: a directory for storing test code and resource files.
    • TestMybatis.java: a Java file for storing test MyBatis.
    • target: a directory for storing compiled Class files, Jar packages, and other files.

    Introduction to the pom.xml file

    Note

    If you only want to verify the example, use the default code without any modifications. You can also modify the pom.xml file according to your needs as described below.

    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 namespace and POM model version.

      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 the <modelVersion> element 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.example.
      2. Use <artifactId> to set the project dependency to java-oceanbase-mybatis.
      3. Use <version> to set the project version to 1.0-SNAPSHOT.

      Sample code:

      <groupId>com.oceanbase.example</groupId>
      <artifactId>java-oceanbase-mybatis</artifactId>
      <version>1.0-SNAPSHOT</version>
      
    4. Use <build> to define the project build process.

      1. Use <plugins> to specify the plugins configured in the project.
      2. Use <plugin> to specify a plugin configured in the project.
      3. Use <groupId> to set the project identifier to org.apache.maven.plugins.
      4. Use <artifactId> to set the project dependency to maven-compiler-plugin.
      5. Use <configuration> to specify the parameters of the configured plugin.
      6. Use <source> to specify the source code version of the compiler as 8.
      7. Use <target> to specify the source code version of the compiler as 8.

      Sample code:

       <build>
           <plugins>
               <plugin>
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-compiler-plugin</artifactId>
                   <configuration>
                       <source>8</source>
                       <target>8</target>
                   </configuration>
               </plugin>
           </plugins>
       </build>
      
    5. Use <dependencies> to define the components on which the project depends.

      1. Set the organization of the dependency to com.oceanbase, the name to oceanbase-client, and the version to 2.4.2.

        Sample code:

            <dependencies>
            <dependency>
                <groupId>com.oceanbase</groupId>
                <artifactId>oceanbase-client</artifactId>
                <version>2.4.2</version>
            </dependency>
            </dependencies>
        
      2. Set the test architecture of the dependency to junit, the name to junit, and the version to 4.10.

        Sample code:

            <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.10</version>
            </dependency>
            </dependencies>
        
      3. Set the architecture of the dependency to org.mybatis, the name to mybatis, and the version to 3.5.9.

        Sample code:

            <dependencies>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.9</version>
            </dependency>
            </dependencies>
        
      4. Set the plugin of the dependency to com.github.pagehelper, the name to pagehelper, and the version to 5.3.0.

        Sample code:

            <dependencies>
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>5.3.0</version>
            </dependency>
            </dependencies>
        

    Introduction to the jdbc.properties file

    The jdbc.properties file is an attribute file used to store configuration information related to the database connection, including the database URL, username, and password. The content of the code is as follows:

    Note

    The values of the fields in the code are obtained directly from Step 1: Obtain the connection string of the OceanBase Cloud database.

    • jdbc.driver: the class name of the database driver program, which is used to load the database driver program.
    • jdbc.url: the URL address of the database, which is used to specify the database to connect to.
    • jdbc.username: the username of the database, which is used to verify the database connection.
    • jdbc.password: the password of the database, which is used to verify the database connection.

    Sample code:

    jdbc.driver=com.oceanbase.jdbc.Driver
    jdbc.url=jdbc:oceanbase://host:port/TEST?useServerPrepStmts=true&rewriteBatchedStatements=true
    jdbc.username=user_name
    jdbc.password=******
    

    Overview of the mybatis-config.xml file

    The mybatis-config.xml file is used to configure global attributes and plugins of the MyBatis framework.

    The code of the mybatis-config.xml file mainly includes the following parts:

    1. File declaration.

      This declaration indicates that the file is an XML file. It also indicates that the current document is a MyBatis configuration file, the XML version is 1.0, and the character encoding is UTF-8. The version number is 3.0, the language is English, and the DTD (Document Type Definition) file provided by the official MyBatis website is used for verification.

      The declaration includes the following parts:

      • version: specifies the version of the XML file.
      • encoding: specifies the encoding method of the XML file.
      • DOCTYPE: declares the type as a document type declaration.
      • configuration: specifies the document type as a MyBatis configuration file.
      • PUBLIC: specifies the document type as a public document type.
      • mybatis.org: indicates the official website of MyBatis.
      • DTD Config 3.0: indicates the version number of the MyBatis configuration file.
      • EN: indicates that the language of the document type is English.

      Sample code:

      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
      
    2. Specify the path and file name of the property file to be loaded.

      <properties resource="jdbc.properties"></properties>
      
    3. Configure global settings of MyBatis.

      The content of global settings of MyBatis includes the following parts:

      • setting: used to configure a single setting item, such as cache and log.
      • cacheEnabled: used to enable or disable the cache feature, set to true.
      • lazyLoadingEnabled: used to enable or disable the lazy loading feature, set to true.
      • aggressiveLazyLoading: used to enable or disable the aggressive lazy loading feature, set to true.
      • multipleResultSetsEnabled: used to configure whether to enable support for multiple result sets, set to true.
      • useColumnLabel: used to configure whether to use column labels as column names in the result set, set to true.
      • useGeneratedKeys: used to configure whether to use automatically generated primary keys, set to true.
      • autoMappingBehavior: used to configure the handling behavior of auto-mapping, set to PARTIAL.
      • defaultExecutorType: used to configure the default executor type, set to SIMPLE.
      • mapUnderscoreToCamelCase: used to configure whether to convert underscores in database column names to camel case in Java object property names, set to true.
      • localCacheScope: used to configure the scope of local cache, set to SESSION.
      • jdbcTypeForNull: used to configure the JDBC type to be used when handling null values, set to NULL.

      Note

      The sub-elements of the settings element are optional and can be added or removed as needed.

      Sample code:

      <settings>
          <!-- Enable or disable caching for global mappers. -->
          <setting name="cacheEnabled" value="true"/>
          <!-- Enable or disable lazy loading globally. When disabled, all associated objects are loaded immediately. -->
          <setting name="lazyLoadingEnabled" value="true"/>
          <!-- When enabled, objects with delayed loading properties will fully load any properties when called. Otherwise, each attribute will be loaded as needed. -->
          <setting name="aggressiveLazyLoading" value="true"/>
          <!-- Allow a single SQL statement to return multiple datasets (depending on driver compatibility) default: true -->
          <setting name="multipleResultSetsEnabled" value="true"/>
          <!-- Can column aliases be used (depending on driver compatibility) default: true -->
          <setting name="useColumnLabel" value="true"/>
          <!-- Allow JDBC to generate primary keys. Drive support is required. If set to true, this setting will force the use of the generated primary key, and some drives may not be compatible but can still be executed. default:false -->
          <setting name="useGeneratedKeys" value="true"/>
          <!-- Specify how MyBatis automatically maps the columns of the data base table NONE: Not Implicit PART: Partial FULL: All -->
          <setting name="autoMappingBehavior" value="PARTIAL"/>
          <!-- This is the default execution type (SIMPLE: simple; REUSE: executor may repeatedly use prepared statements; BATCH: executor can repeatedly execute statements and batch updates) -->
          <setting name="defaultExecutorType" value="SIMPLE"/>
          <!-- Convert fields using camel naming. -->
          <setting name="mapUnderscoreToCamelCase" value="true"/>
          <!-- Set the local cache range session: there will be data sharing statement: statement range (so there will be no data sharing) defalut: session -->
          <setting name="localCacheScope" value="SESSION"/>
          <!-- When the JDBC type is set to null, some drivers need to specify a value, default: Other, and there is no need to specify a type when inserting null values -->
          <setting name="jdbcTypeForNull" value="NULL"/>
      </settings>
      
    4. Configure plugins of MyBatis.

      The content of plugins of MyBatis includes the following parts:

      • plugin: used to configure a single plugin.
      • property: used to specify the properties of the plugin.
      • interceptor: used to specify the implementation class of the plugin.
      • helperDialect: used to specify the selected database.
      • offsetAsPageNum: indicates whether to use the offset parameter as the pageNum parameter.
      • rowBoundsWithCount: indicates whether to perform a count query.
      • pageSizeZero: indicates whether to support queries with a page size of 0.
      • reasonable: indicates whether to enable reasonable query optimization.
      • params: indicates the mapping relationship between the parameter name and parameter value for passing pagination parameters.
      • supportMethodsArguments: indicates whether to support using method parameters to pass pagination parameters.
      • returnPageInfo: indicates the return value type.

      Sample code:

      <plugin interceptor="com.github.pagehelper.PageInterceptor">
         <!-- this parameter indicates which database to connect to -->
         <!--MySQLMode dialect<property name="helperDialect" value="mysql"/>-->
         <!--OracleMode dialect -->
         <property name="helperDialect" value="oracle"/>
         <!-- This parameter defaults to false. When set to true, the first parameter offset of RowBounds will be used as the pageNum page number, similar to the pageNum effect in startPage -->
         <property name="offsetAsPageNum" value="true"/>
         <!-- This parameter defaults to false, and when set to true, using RowBounds pagination will result in a count query -->
         <property name="rowBoundsWithCount" value="true"/>
         <!-- When set to true, if pageSize=0 or RowBounds. limit=0, all results will be queried (equivalent to not executing a pagination query, but the returned results are still of type Page) -->
         <property name="pageSizeZero" value="true"/>
         <!-- Version 3.3.0 is available - pagination parameter rationalization is disabled by default as false. When rationalization is enabled, if pageNum<1, the first page will be queried, and if pageNum>pages, the last page will be queried. Rationalization of paging parameters. When rationalization is disabled, if pageNum<1 or pageNum>pages returns empty data -->
         <property name="reasonable" value="false"/>
         <!-- Version 3.5.0 is available - In order to support the startPage (Object params) method, a 'params' parameter has been added to configure parameter mapping, which can be used to retrieve values from Map or ServletRequest. PageNum, pageSize, count, pageSizeZero, reasonable, orderBy can be configured. If mapping is not configured, the default value will be used. If you do not understand the meaning, do not copy this configuration casually -->
         <property name="params" value="pageNum=start;pageSize=limit;"/>
         <!-- Support passing paging parameters through Mapper interface parameters -->
         <property name="supportMethodsArguments" value="true"/>
         <!-- Always always returns PageInfo type, check to check if the return type is PageInfo, and none returns Page -->
         <property name="returnPageInfo" value="check"/>
      </plugin>
      
    5. Configure the environment of MyBatis. The content of the environment of MyBatis includes the following parts:

      • environment: used to configure a single environment.
      • transactionManager: used to specify the implementation class of the transaction manager.
      • dataSource: used to specify the implementation class of the data source.
      • property: specifies the class name of the database driver.

      Note

      In other configuration elements of MyBatis, you can use ${} placeholders to reference data sources, transaction managers, and executors configured in the environment.

      Sample code:

      <environments default="development">
          <environment id="development">
            <transactionManager type="JDBC"/>
              <dataSource type="POOLED">
                  <property name="driver" value="${jdbc.driver}"/>
                  <property name="url" value="${jdbc.url}"/>
                  <property name="username" value="${jdbc.username}"/>
                  <property name="password" value="${jdbc.password}"/>
              </dataSource>
          </environment>
      </environments>
      
    6. Configure the mapper of MyBatis.

      The commonly used elements of the mapper of MyBatis are as follows:

      • resource: used to specify the path and file name of the XML configuration file of the mapper.
      • class: used to specify the fully qualified name of the Java class of the mapper.

      Note

      If you use an XML configuration file, you need to specify the path and file name of the XML file in the mapper element. If you use a Java interface, you need to specify the fully qualified name of the Java class in the mapper element.

      Sample code:

      <mappers>
        <!-- IUserMapper.xml mapping file -->
        <mapper resource="com/alipay/oceanbase/mapper/IUserMapper.xml"></mapper>
        <!-- IAppMapper mapping class -->
        <mapper class="com.oceanbase.mapper.IAppMapper"></mapper>
      </mappers>
      

    Introduction to the code in the IUserMapper.xml file

    The IUserMapper.xml file is a mapping file that defines SQL statements related to the user object. The file defines a namespace named IUserMapper to store SQL statements related to the user object.

    Note

    If you want to verify the example, use the default code without any modifications. If you need to modify the code, adjust it based on your specific requirements.

    The code in the IUserMapper.xml file mainly includes the following parts:

    1. File declaration statements. The XML declaration specifies the version and encoding method of the XML file. The DTD declaration introduces the DTD file of MyBatis. Sample code:

      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE mapper
           PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
           "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      
    2. Configure the mapping relationship with the IUserMapper.java file.

      1. Define the namespace of the Mapper interface to correspond with the Mapper interface in the Java code.
      2. Create an SQL statement named insertUser to insert a record into the test_user table, including the id and name fields, with values #{id} and #{name} respectively. The parameterType attribute specifies the parameter type as com.oceanbase.pojo.User.
      3. Create an SQL statement named deleteUser to delete a record from the test_user table based on the value of the id field, which is #{id}.
      4. Create an SQL statement named updateUser to update the name field to #{name} in the test_user table based on the value of the id field, which is #{id}.
      5. Create an SQL statement named selectUsers to query all user records from the test_user table.
      6. Create an SQL statement named selectUserByPage to query user objects from the test_user table for a specified page. Use subqueries and the rownum field for pagination. #{pageNum} and #{pageSize} represent the current page number and the number of records per page, respectively.

      Sample code:

      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE mapper
              PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
              "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <mapper namespace="com.oceanbase.mapper.IUserMapper">
          <insert id="insertUser" parameterType="com.oceanbase.pojo.User">
              INSERT INTO test_user (id,name) VALUES (#{id},#{name})
          </insert>
          <delete id="deleteUser" parameterType="long">
              DELETE FROM test_user WHERE id = #{id}
          </delete>
          <update id="updateUser" parameterType="com.oceanbase.pojo.User">
              UPDATE test_user SET name = #{name} WHERE id = #{id}
          </update>
          <select id="selectUsers" resultType="com.oceanbase.pojo.User">
              SELECT id,name FROM test_user
          </select>
          <!--    There are two ways to paginate queries: 1. Use the pagehelper plugin; 2. Use SQL statements to paginate  -->
          <!-- SQL statement pagination: Oracle compatible mode does not support the limit keyword, and instead uses the unique field 'rownum'-->
          <select id="selectUserByPage" resultType="com.oceanbase.pojo.User">
              select id,name from ( select row_.*, rownum rownum_ from ( select * from test_user ) row_ where rownum
              <![CDATA[ <= ]]>  #{pageNum} * #{pageSize} ) where rownum_ <![CDATA[ >]]>  ( #{pageNum}- 1) * #{pageSize}
          </select>
      </mapper>
      

    Introduction to the code in the IAppMapper.java file

    The IAppMapper.java file is used to define SQL mapping relationships.

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

    1. Define the Mapper package.

      Declare the package name of the current file as com.oceanbase.mapper. The Mapper package contains the following interfaces and classes:

      • App interface: Represents the mapping between a database table and data read/write operations.
      • org.apache.ibatis.annotations.*: Used to import the annotation classes of MyBatis.
      • java.util.List: Used to import the List class from the java.util package. Sample code:
      package com.oceanbase.mapper;
      import com.oceanbase.pojo.App;
      import org.apache.ibatis.annotations.*;
      import java.util.List;
      
    2. Define the IAppMapper interface. The IAppMapper interface is used to define the Mapper interface of MyBatis. The Mapper interface is used to define SQL mapping relationships and perform database operations such as adding, deleting, modifying, and querying data. Specifically, the IAppMapper interface defines methods for adding, deleting, modifying, and querying data in the test_app table, including:

      • @Insert method: Used to insert data into the database.
      • @Update method: Used to update data in the database.
      • @Delete method: Used to delete data from the database.
      • @Select method: Used to query data from the database.
      • @Results method: Represents the mapping relationship of query results. It is used to map fields in the query results to properties of Java objects. Database operations such as adding, deleting, modifying, and querying data are as follows:
      1. Insert data Map the App object to a record in the test_app table. Use #{attribute name} to represent the attribute values of the App object. The Integer return value represents the automatically generated ID returned by the SQL statement after inserting data, which is the value of the ID field in the test_app table.

        @Insert("insert into test_app(id,name) values(#{id},#{name})")
        Integer insertApp(App app);
        
      2. Delete data Delete data with an ID equal to #{id} from the test_app table.

        @Delete("delete from test_app  where id =#{id}")
        Integer deleteApp(Long id);
        
      3. Update data Perform an Update operation to modify records in the test_app table.

        @Update("update test_app set name= #{name} where id = #{id}")
        Integer updateApp(App user);
        
      4. Query and map data Query all data from the test_app table. Use the @Results and @Result annotations to map the query results to the id and name properties of the App object. Return a list of App objects.

        @Update("update test_app set name= #{name} where id = #{id}")
        Integer updateApp(App user);
        @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "name", property = "name")
            })
        List<App> selectApps();
        

      Sample code:

      package com.oceanbase.mapper;
      import com.oceanbase.pojo.App;
      import org.apache.ibatis.annotations.*;
      import java.util.List;
      public interface IAppMapper {
          @Insert("insert into test_app(id,name) values(#{id},#{name})")
          Integer insertApp(App app);
      
          @Delete("delete from test_app  where id =#{id}")
          Integer deleteApp(Long id);
      
          @Update("update test_app set name= #{name} where id = #{id}")
          Integer updateApp(App user);
      
          @Select("select * from test_app")
          @Results({
                  @Result(id = true, column = "id", property = "id"),
                  @Result(column = "name", property = "name")
          })
          List<App> selectApps();
      }
      

    Introduction to the code in the IUserMapper.java file

    The IUserMapper.java file is used to define database operation methods.

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

    1. Import other classes and interfaces.

      Declare the interfaces and classes included in the current file:

      • User class: Represents the user object.
      • org.apache.ibatis.annotations.Param class: A parameter annotation in the MyBatis framework.
      • List interface: Represents a list type. Sample code:
      package com.oceanbase.mapper;
      import com.oceanbase.pojo.User;
      import org.apache.ibatis.annotations.Param;
      import java.util.List;
      
    2. Define the IUserMapper interface.

      Define an interface named IUserMapper that includes methods for inserting, deleting, updating, and querying user data, as well as methods for paginated queries. Use JavaDoc comments and the @Param annotation to improve code readability and maintainability. Sample code:

       public interface IUserMapper {
      
           Integer insertUser(User user);
      
           Integer deleteUser(Long id);
      
           Integer updateUser(User user);
      
           List<User> selectUsers();
      
           public List<User> selectUserByPage(@Param("user") User user, @Param("pageNum") Integer pageNum,
                                           @Param("pageSize") Integer pageSize);
       }
      

    App.java code introduction

    The App.java file is used to represent the App application object. It includes two properties, id and name. The class also defines access methods for the properties, a constructor method, and a toString method for converting the object to a string.

    The App.java file contains the following parts:

    1. Define the pojo package. Declare the package name of the current file as com.oceanbase.pojo.
    2. Define the App class.
      1. Define a class App with two private properties, id and name, and a parameterless constructor method public App(){}.
      2. Define a parameterized constructor method public App(Long id, String name) for creating an application object with the specified id and name.
      3. Define the getId, setId, getName, and setName methods for retrieving and setting the application name. The setName method returns the name of the application.
      4. Override the toString method to convert the application object to a string representation for easy output and debugging.

    Sample code:

       package com.oceanbase.pojo;
    
       public class App {
           private Long id;
           private String name;
    
           public App() {
           }
    
           public App(Long id, String name) {
                this.id = id;
               this.name = name;
           }
    
           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;
           }
    
           @Override
           public String toString() {
               return "App{" +
                       "id=" + id +
                       ", name='" + name + '\'' +
                       '}';
           }
       }
    

    User.java code introduction

    The User.java file is used to represent the user object. It includes two properties, id and name. The class also defines access methods for the properties, a constructor method, and a toString method for converting the object to a string. The creation of this class is similar to that of the App.java file.

    Sample code:

    package com.oceanbase.pojo;
    
    public class User {
        private Long id;
        private String name;
    
        public User() {
        }
    
        public User(Long id, String name) {
            this.id = id;
            this.name = name;
        }
    
        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;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    

    Overview of the MyBatisTest.java file

    The MyBatisTest.java file is used to demonstrate how to use MyBatis for data operations. It tests the basic functionality of the MyBatis framework, the execution of SQL statements, and the calling methods of the Mapper interface, including parameters and return values of SQL statements.

    1. Import other classes and interfaces.

      The following classes and interfaces are imported:

      • IAppMapper interface: defines SQL statements related to App objects.
      • IUserMapper interface: defines SQL statements related to User objects.
      • App class: an App object used to test the execution of SQL statements.
      • User class: a User object used to test the execution of SQL statements.
      • PageHelper plugin: implements the pagination query feature.
      • PageInfo plugin: encapsulates the results of pagination queries.
      • Resources class: loads the MyBatis configuration file.
      • SqlSession class: executes SQL statements and manages transactions.
      • SqlSessionFactory class: creates a SqlSession object.
      • SqlSessionFactoryBuilder class: creates a SqlSessionFactory object.
      • org.junit.Test: an annotation of the JUnit testing framework used to mark test methods.
      • IOException class: represents errors during input and output operations.
      • SQLException class: represents errors during SQL operations.
      • Statement interface: executes SQL statements and returns results.
      • java.util.List interface: represents an ordered collection where elements can be repeated.

      Code:

      import com.oceanbase.mapper.IAppMapper;
      import com.oceanbase.mapper.IUserMapper;
      import com.oceanbase.pojo.App;
      import com.oceanbase.pojo.User;
      import com.github.pagehelper.PageHelper;
      import com.github.pagehelper.PageInfo;
      import org.apache.ibatis.io.Resources;
      import org.apache.ibatis.session.SqlSession;
      import org.apache.ibatis.session.SqlSessionFactory;
      import org.apache.ibatis.session.SqlSessionFactoryBuilder;
      import org.junit.Test;
      import java.io.IOException;
      import java.sql.SQLException;
      import java.sql.Statement;
      import java.util.List;
      
    2. Define the testUserMapper method.

      The testUserMapper method is used to test the execution of SQL statements defined in the Mapper interface of the User object.

      1. Use the build() method of the SqlSessionFactoryBuilder class to create a SqlSessionFactory instance. This instance is used to manage the creation and destruction of SqlSession instances.
      2. Use the openSession() method of the SqlSessionFactory class to create a SqlSession instance. This instance can execute various SQL statements, including queries, inserts, updates, and deletes.
      3. Use the getConnection() method of the SqlSession instance to obtain a Connection instance. This instance can execute various database operations.
      4. Use the createStatement() method of the Connection instance to create a Statement instance. Execute SQL statements in sequence.
      5. Use the execute() method of the Statement object to execute an SQL statement to delete the test_user table.
      6. Use the execute() method of the Statement object to create a test_user table. This table contains two fields: one is id, of type number(20), which serves as the primary key; the other is name, of type varchar2(100).
      7. Use the getMapper() method of the SqlSession instance to obtain an instance of the IUserMapper interface. Define various database operation methods.
      8. Use a for loop to insert 10 records into the test_user table. In each iteration, create a new User object, use the insertUser() method of the Mapper interface to execute the insert operation. The result of the insert operation is stored in the insertResult variable.
      9. Delete, update, and query data in the test_user table, and finally use the forEach() method to print the information of each user in the user list.
      10. Create a user named insert, use the selectUserByPage() method to query all users named "insert" in the test_user table, and return the user list of the specified page. Query the second page, with 3 records displayed per page. Print these user data to the console. Close the Statement and SqlSession instances, commit the transaction, and release resources.

      Code:

          public void testUserMapper() throws SQLException, IOException {
              //mybatis xml usecases
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
              SqlSession sqlSession = sqlSessionFactory.openSession();
              Statement statement = sqlSession.getConnection().createStatement();
              try {
                  statement.execute("drop table test_user");
              } catch (SQLException ex) {
              } finally {
                  statement.execute("create table test_user(id number(20) primary key,name varchar2(100))");
              }
              IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
              //insert 10 users
              for (int i = 1; i <= 10; i++) {
                  User user = new User((long) i, "insert");
                  Integer insertResult = mapper.insertUser(user);
              }
              //delete id==1
              Integer deleteResult = mapper.deleteUser(1L);
              //update id==2L name=update
              User updateUser = new User(2L, "update");
              Integer updateResult = mapper.updateUser(updateUser);
              //selectUsers query all
              List<User> userList = mapper.selectUsers();
              userList.forEach(System.out::println);
              //selectUsersByPage: use the rownum keyword in SQL statements to manually perform pagination queries,
              // example: data on page 2 (3 items per page)
              User user = new User();
              user.setName("insert");
              List<User> usersByPage = mapper.selectUserByPage(user, 2, 3);
              System.out.println("usersByPage = " + usersByPage);
              statement.close();
              sqlSession.commit();
              sqlSession.close();
          }
      
    3. Define the testSqlSession method.

      The testSqlSession method is used to test the basic functionality of the SqlSession object, including executing SQL statements, committing transactions, and closing the SqlSession object.

      1. Use the build() method of the SqlSessionFactoryBuilder class to create a SqlSessionFactory instance. This instance is used to manage the creation and destruction of SqlSession instances.
      2. Use the openSession() method of the SqlSessionFactory instance to create a SqlSession instance. This instance can execute various SQL statements, including queries, inserts, updates, and deletes.
      3. Use the getConnection() method of the SqlSession instance to obtain a Connection instance. This instance can execute various database operations.
      4. Use the createStatement() method of the Connection instance to create a Statement instance. Execute SQL statements in sequence.
      5. Use the execute() method of the Statement object to execute an SQL statement for deleting the test_user table.
      6. Use the execute() method of the Statement object to create the test_user table. This table contains two fields: id of type number(20) as the primary key, and name of type varchar2(100).
      7. Use a for loop to insert 10 records into the test_user table. In each iteration of the loop, create a new User object, call the insertUser() method of the Mapper interface, and execute the insert operation. The result of the insert operation will be stored in the insertResult variable.
      8. Use the delete() method of the sqlSession object to execute a delete operation. Set the deletion condition by passing the parameter 1L. The result of the delete operation will be stored in the deleteResult variable.
      9. Use the sqlSession object to execute a database update operation. Create a User object, call the update method by passing the SQL statement identifier and parameter object, and complete the update operation. The specific SQL statements and parameter mapping relationships can be found in the XML configuration file of the "com.oceanbase.mapper.IUserMapper" interface. The result of the update operation will be stored in the updateResult variable.
      10. Use the openSession() method of the SqlSessionFactory instance to create a SqlSession instance. Execute a query operation through this instance and store the query result in the userList variable. Finally, use the forEach method to traverse the userList and output the result to the console.
      11. Close the Statement object in the database connection by calling the statement.close() method. Then, call the sqlSession.commit() method to commit the transaction and persist all modifications to the database. Finally, close the SqlSession object by calling the sqlSession.close() method to release the related resources and close the connection to the database.

      Sample code:

          public void testSqlSession() throws SQLException, IOException {
              //SqlSession usecases
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
              SqlSession sqlSession = sqlSessionFactory.openSession();
              Statement statement = sqlSession.getConnection().createStatement();
              try {
                  statement.execute("drop table test_user");
              } catch (SQLException ex) {
              } finally {
                  statement.execute("create table test_user(id number(20) primary key,name varchar2(100))");
              }
              //insert
              for (int i = 1; i <= 10; i++) {
                  User user = new User((long) i, "insert");
                  //Integer insertResult = mapper.insertUser(user);
                  int insertResult = sqlSession.insert("com.oceanbase.mapper.IUserMapper.insertUser", user);
              }
              //delete
              int deleteResult = sqlSession.delete("com.oceanbase.mapper.IUserMapper.deleteUser", 1L);
              //update
              User updateUser = new User(2L, "update");
              int updateResult = sqlSession.update("com.oceanbase.mapper.IUserMapper.updateUser", updateUser);
              //selectUsers
              List<User> userList = sqlSession.selectList("com.oceanbase.mapper.IUserMapper.selectUsers", null);
              userList.forEach(System.out::println);
              //System.out.println("userList = " + userList);
              statement.close();
              sqlSession.commit();
              sqlSession.close();
          }
      
    4. Define the testAppMapper method.

      The testAppMapper method is used to test the functionality of AppMapper.

      1. Use the build() method of the SqlSessionFactoryBuilder class to create a SqlSessionFactory instance. This instance is used to manage the creation and destruction of SqlSession instances.
      2. Use the openSession() method of the SqlSessionFactory instance to create a SqlSession instance. This instance can execute various SQL statements, including queries, inserts, updates, and deletes.
      3. Use the getConnection() method of the SqlSession instance to obtain a Connection instance. This instance can execute various database operations.
      4. Use the createStatement() method of the Connection instance to create a Statement instance. Execute SQL statements in sequence.
      5. Use the execute() method of the Statement object to execute an SQL statement for deleting the test_app table.
      6. Use the execute() method of the Statement object to create the test_app table. This table contains two fields: id of type number(20) as the primary key, and name of type varchar2(100).
      7. Use the getMapper() method of the SqlSession instance to obtain an instance of the IAppMapper interface. Define various database operation methods.
      8. Use a for loop to insert 10 records into the test_app table. In each iteration of the loop, create a new App object, call the insertApp() method of the Mapper interface, and execute the insert operation. The result of the insert operation will be stored in the insertResult variable.
      9. Use the delete() method of the mapper object to execute a delete operation. Set the deletion condition by passing the parameter 1L. The result of the delete operation will be stored in the deleteResult variable.
      10. Use the mapper object to execute a database update operation. Create an App object, call the update method by passing the SQL statement identifier and parameter object, and complete the update operation.
      11. Create an App object named updateApp with id set to 2L and name set to "update".
      12. Call the updateApp method of the mapper object and pass the updateApp object to execute the update operation.
      13. Call the commit method of the sqlSession object to commit the database transaction.
      14. Call the selectApps method of the mapper object to query all App objects. Use the forEach method to traverse the userList and output the result to the console.
      15. Call the startPage method of the PageHelper object and pass the page number and number of records per page to set the pagination parameters. Query all App objects and return a List object containing all App objects.
      16. Call the getList method of the PageInfo object to obtain the paginated App object list. Use the System.out.println method to print and output the paginated App object list.
      17. Close the SqlSession object by calling the sqlSession.close() method to release the related resources.

      Sample code:

          public void testAppMapper() throws SQLException, IOException {
              //mybatis annotation usecases
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
              SqlSession sqlSession = sqlSessionFactory.openSession();
              Statement statement = sqlSession.getConnection().createStatement();
              try {
                  statement.execute("drop table test_app");
              } catch (SQLException ex) {
              } finally {
                  statement.execute("create table test_app(id number(20) primary key,name varchar2(100))");
              }
      
              IAppMapper mapper = sqlSession.getMapper(IAppMapper.class);
      
              //insert
              for (int i = 1; i <= 10; i++) {
                  App app = new App((long) i, "insert" + i);
                  Integer insertResult = mapper.insertApp(app);
              }
      
              //delete
              Integer deleteResult = mapper.deleteApp(1L);
              //update
              App updateApp = new App(2L, "update");
              Integer updateResult = mapper.updateApp(updateApp);
              //commit
              sqlSession.commit();
      
              //selectApps
              List<App> appList = mapper.selectApps();
              appList.forEach(System.out::println);
      
              //selectbyPage
              //set page parameters
              PageHelper.startPage(2, 3);
              //selectApps
              List<App> appList1 = mapper.selectApps();
              //get pageList
              PageInfo pageInfo = new PageInfo(appList1);
              List<App> pageList = pageInfo.getList();
              System.out.println("pageList = " + pageList);
      
              sqlSession.close();
          }
      

    Full code

    pom.xml
    jdbc.properties
    mybatis-config.xml
    IUserMapper.xml
    IAppMapper.java
    IUserMapper.java
    App.java
    User.java
    TestMybatis.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.example</groupId>
            <artifactId>java-oceanbase-mybatis</artifactId>
            <version>1.0-SNAPSHOT</version>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <configuration>
                            <source>8</source>
                            <target>8</target>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
    
            <dependencies>
                <dependency>
                    <groupId>com.oceanbase</groupId>
                    <artifactId>oceanbase-client</artifactId>
                    <version>2.4.2</version>
                </dependency>
                <dependency>
                    <groupId>junit</groupId>
                    <artifactId>junit</artifactId>
                    <version>4.10</version>
                </dependency>
                <dependency>
                    <groupId>org.mybatis</groupId>
                    <artifactId>mybatis</artifactId>
                    <version>3.5.9</version>
                </dependency>
                <!--  pagehelper plug-in -->
                <dependency>
                    <groupId>com.github.pagehelper</groupId>
                    <artifactId>pagehelper</artifactId>
                    <version>5.3.0</version>
                </dependency>
            </dependencies>
        </project>
    
    jdbc.driver=com.oceanbase.jdbc.Driver
    jdbc.url=jdbc:oceanbase://host:port/TEST?useServerPrepStmts=true&rewriteBatchedStatements=true
    jdbc.username=user_name
    jdbc.password=******
    
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
        <configuration>
          <properties resource="jdbc.properties"></properties>
          <settings>
              <setting name="cacheEnabled" value="true"/>
              <setting name="lazyLoadingEnabled" value="true"/>
              <setting name="aggressiveLazyLoading" value="true"/>
              <setting name="multipleResultSetsEnabled" value="true"/>
              <setting name="useColumnLabel" value="true"/>
              <setting name="useGeneratedKeys" value="true"/>
              <setting name="autoMappingBehavior" value="PARTIAL"/>
              <setting name="defaultExecutorType" value="SIMPLE"/>
              <setting name="mapUnderscoreToCamelCase" value="true"/>
              <setting name="localCacheScope" value="SESSION"/>
              <setting name="jdbcTypeForNull" value="NULL"/>
          </settings>
          <plugins>
              <plugin interceptor="com.github.pagehelper.PageInterceptor">
    
                  <property name="helperDialect" value="oracle"/>
    
                  <property name="offsetAsPageNum" value="true"/>
                  <property name="rowBoundsWithCount" value="true"/>
                  <property name="pageSizeZero" value="true"/>
    
                  <property name="reasonable" value="false"/>
    
                  <property name="params" value="pageNum=start;pageSize=limit;"/>
                  <property name="supportMethodsArguments" value="true"/>
                  <property name="returnPageInfo" value="check"/>
              </plugin>
          </plugins>
          <environments default="development">
              <environment id="development">
                  <transactionManager type="JDBC"/>
                  <dataSource type="POOLED">
                      <property name="driver" value="${jdbc.driver}"/>
                      <property name="url" value="${jdbc.url}"/>
                      <property name="username" value="${jdbc.username}"/>
                      <property name="password" value="${jdbc.password}"/>
                  </dataSource>
              </environment>
          </environments>
          <mappers>
              <mapper resource="com/alipay/oceanbase/mapper/IUserMapper.xml"></mapper>
              <mapper class="com.oceanbase.mapper.IAppMapper"></mapper>
          </mappers>
        </configuration>
    
        <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        <mapper namespace="com.oceanbase.mapper.IUserMapper">
            <insert id="insertUser" parameterType="com.oceanbase.pojo.User">
                INSERT INTO test_user (id,name) VALUES (#{id},#{name})
            </insert>
            <delete id="deleteUser" parameterType="long">
                DELETE FROM test_user WHERE id = #{id}
            </delete>
            <update id="updateUser" parameterType="com.oceanbase.pojo.User">
                UPDATE test_user SET name = #{name} WHERE id = #{id}
            </update>
            <select id="selectUsers" resultType="com.oceanbase.pojo.User">
                SELECT id,name FROM test_user
            </select>
            <!--    There are two ways to paginate queries: 1. Use the pagehelper plugin; 2. Use SQL statements to paginate  -->
            <!-- SQL statement pagination: Oracle compatible mode does not support the limit keyword, and instead uses the unique field 'rownum'-->
            <select id="selectUserByPage" resultType="com.oceanbase.pojo.User">
                select id,name from ( select row_.*, rownum rownum_ from ( select * from test_user ) row_ where rownum
                <![CDATA[ <= ]]>  #{pageNum} * #{pageSize} ) where rownum_ <![CDATA[ >]]>  ( #{pageNum}- 1) * #{pageSize}
            </select>
        </mapper>
    
    package com.oceanbase.mapper;
    
    import com.oceanbase.pojo.App;
    import org.apache.ibatis.annotations.*;
    
    import java.util.List;
    
    //using annotations
    public interface IAppMapper {
        @Insert("insert into test_app(id,name) values(#{id},#{name})")
        Integer insertApp(App app);
    
        @Delete("delete from test_app  where id =#{id}")
        Integer deleteApp(Long id);
    
        @Update("update test_app set name= #{name} where id = #{id}")
        Integer updateApp(App user);
    
        @Select("select * from test_app")
        @Results({
                @Result(id = true, column = "id", property = "id"),
                @Result(column = "name", property = "name")
        })
        List<App> selectApps();
    }
    
    package com.oceanbase.mapper;
    
    import com.oceanbase.pojo.User;
    import org.apache.ibatis.annotations.Param;
    
    import java.util.List;
    
    //using XML
    public interface IUserMapper {
    
        Integer insertUser(User user);
    
    
        Integer deleteUser(Long id);
    
        Integer updateUser(User user);
    
    
        List<User> selectUsers();
    
    
        public List<User> selectUserByPage(@Param("user") User user, @Param("pageNum") Integer pageNum,
                                           @Param("pageSize") Integer pageSize);
    }
    
    package com.oceanbase.pojo;
    
    public class App {
        private Long id;
        private String name;
    
        public App() {
        }
    
        public App(Long id, String name) {
            this.id = id;
            this.name = name;
        }
    
        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;
        }
    
        @Override
        public String toString() {
            return "App{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    
    package com.oceanbase.pojo;
    
    public class User {
        private Long id;
        private String name;
    
        public User() {
        }
    
        public User(Long id, String name) {
            this.id = id;
            this.name = name;
        }
    
        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;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    
    import com.oceanbase.mapper.IAppMapper;
    import com.oceanbase.mapper.IUserMapper;
    import com.oceanbase.pojo.App;
    import com.oceanbase.pojo.User;
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.List;
    
    
    public class TestMybatis {
        @Test
        public void testUserMapper() throws SQLException, IOException {
            //mybatis xml usecases
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Statement statement = sqlSession.getConnection().createStatement();
            try {
                statement.execute("drop table test_user");
            } catch (SQLException ex) {
            } finally {
                statement.execute("create table test_user(id number(20) primary key,name varchar2(100))");
            }
            IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
            //insert 10 users
            for (int i = 1; i <= 10; i++) {
                User user = new User((long) i, "insert");
                Integer insertResult = mapper.insertUser(user);
            }
            //delete id==1
            Integer deleteResult = mapper.deleteUser(1L);
            //update id==2L name=update
            User updateUser = new User(2L, "update");
            Integer updateResult = mapper.updateUser(updateUser);
            //selectUsers query all
            List<User> userList = mapper.selectUsers();
            userList.forEach(System.out::println);
            //selectUsersByPage: use the rownum keyword in SQL statements to manually perform pagination queries,
            // example: data on page 2 (3 items per page)
            User user = new User();
            user.setName("insert");
            List<User> usersByPage = mapper.selectUserByPage(user, 2, 3);
            System.out.println("usersByPage = " + usersByPage);
            statement.close();
            sqlSession.commit();
            sqlSession.close();
        }
    
        @Test
        public void testSqlSession() throws SQLException, IOException {
            //SqlSession usecases
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Statement statement = sqlSession.getConnection().createStatement();
            try {
                statement.execute("drop table test_user");
            } catch (SQLException ex) {
            } finally {
                statement.execute("create table test_user(id number(20) primary key,name varchar2(100))");
            }
            //insert
            for (int i = 1; i <= 10; i++) {
                User user = new User((long) i, "insert");
                //Integer insertResult = mapper.insertUser(user);
                int insertResult = sqlSession.insert("com.oceanbase.mapper.IUserMapper.insertUser", user);
            }
            //delete
            int deleteResult = sqlSession.delete("com.oceanbase.mapper.IUserMapper.deleteUser", 1L);
            //update
            User updateUser = new User(2L, "update");
            int updateResult = sqlSession.update("com.oceanbase.mapper.IUserMapper.updateUser", updateUser);
            //selectUsers
            List<User> userList = sqlSession.selectList("com.oceanbase.mapper.IUserMapper.selectUsers", null);
            userList.forEach(System.out::println);
            //System.out.println("userList = " + userList);
            statement.close();
            sqlSession.commit();
            sqlSession.close();
        }
    
        @Test
        public void testAppMapper() throws SQLException, IOException {
            //mybatis annotation usecases
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Statement statement = sqlSession.getConnection().createStatement();
            try {
                statement.execute("drop table test_app");
            } catch (SQLException ex) {
            } finally {
                statement.execute("create table test_app(id number(20) primary key,name varchar2(100))");
            }
    
            IAppMapper mapper = sqlSession.getMapper(IAppMapper.class);
    
            //insert
            for (int i = 1; i <= 10; i++) {
                App app = new App((long) i, "insert" + i);
                Integer insertResult = mapper.insertApp(app);
            }
    
            //delete
            Integer deleteResult = mapper.deleteApp(1L);
            //update
            App updateApp = new App(2L, "update");
            Integer updateResult = mapper.updateApp(updateApp);
            //commit
            sqlSession.commit();
    
            //selectApps
            List<App> appList = mapper.selectApps();
            appList.forEach(System.out::println);
    
            //selectbyPage
            //set page parameters
            PageHelper.startPage(2, 3);
            //selectApps
            List<App> appList1 = mapper.selectApps();
            //get pageList
            PageInfo pageInfo = new PageInfo(appList1);
            List<App> pageList = pageInfo.getList();
            System.out.println("pageList = " + pageList);
    
            sqlSession.close();
        }
    }
    

    References

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

    Previous topic

    Connect to OceanBase Cloud by using Hibernate
    Last

    Next topic

    Use JFinal to connect to OceanBase Cloud
    Next
    What is on this page
    Prerequisites
    Procedure
    Step 1: Obtain the connection string of the OceanBase Cloud database
    Step 2: Import the java-oceanbase-mybatis project into IntelliJ IDEA
    Step 3: Modify the database connection information in the java-oceanbase-mybatis project
    Step 4: Run the java-oceanbase-mybatis project
    Project code
    Introduction to the pom.xml file
    Introduction to the jdbc.properties file
    Overview of the mybatis-config.xml file
    Introduction to the code in the IUserMapper.xml file
    Introduction to the code in the IAppMapper.java file
    Introduction to the code in the IUserMapper.java file
    App.java code introduction
    User.java code introduction
    Overview of the MyBatisTest.java file
    Full code
    References