OceanBase
English日本語简体中文
Docs Home
Products
Integrations
Release Notes

Databases

OceanBase DatabaseOceanBase Cloud OceanBase Best Practices

Tools

OceanBase Cloud PlatformOceanBase Migration ServiceOceanBase Developer CenterOceanBase Migration AssessmentOceanBase Admin ToolOceanBase Loader and DumperOceanBase DeployerKubernetes operator for OceanBaseOceanBase Diagnostic Tool OceanBase Binlog Service

Connectors and Middleware

OceanBase Database Proxy OceanBase Connector/C OceanBase Connector/J OceanBase Connector/ODBC OceanBase Connector/NETOceanBase Command-Line Client

Databases

OceanBase DatabaseOceanBase Cloud OceanBase Best Practices

Connectors and Middleware

OceanBase Database Proxy OceanBase Connector/C OceanBase Connector/J OceanBase Connector/ODBC OceanBase Connector/NETOceanBase Command-Line Client

Tools

OceanBase Cloud PlatformOceanBase Migration ServiceOceanBase Developer CenterOceanBase Migration AssessmentOceanBase Admin ToolOceanBase Loader and DumperOceanBase DeployerKubernetes operator for OceanBaseOceanBase Diagnostic Tool OceanBase Binlog Service
OceanBase DatabaseOceanBase Cloud ToolsConnectors and MiddlewareLifecycle Support Policy

OceanBase Database

  • Overview of the ecosystem
  • ORM frameworks
    • Java
      • Spring Boot
      • Spring Batch
      • Use Spring JDBC to connect to OceanBase Database
      • Spring Data JPA
      • Hibernate
      • MyBatis
      • jOOQ
    • Python
      • Use SQLAlchemy to connect to OceanBase Database
      • Connect to OceanBase Database by using peewee
      • Use Tortoise ORM to connect to OceanBase Database
    • Go
      • Connect to OceanBase Database by using GORM
      • beego ORM
    • Rust
      • SeaORM Connection to OceanBase Database
      • Diesel Connection to OceanBase Database
    • Ruby
      • Active Record
      • Sequel Connection to OceanBase Database
      • Connect to OceanBase Database by using Ruby on Rails
    • Node.js
      • Sequelize
      • TypeORM
      • Prisma
      • Drizzle
    • C#
      • Dapper
      • SqlSugar
      • FreeSQL
    • PHP
      • Connect to OceanBase Database by using the Yii 2.0 ORM
      • Connect to OceanBase Database by using Laravel Eloquent ORM
      • CakePHP
  • Database version management
    • Liquibase
    • Flyway
  • Data integration
    • Flink
      • Apache Flink
      • Flink DirectLoad
      • Flink Connector OceanBase
    • dbt
    • SeaTunnel
    • Maxwell
    • Debezium
    • Spark Catalog
    • NiFi
    • Qlik Replicate
    • RisingWave CDC
    • Flume
    • Migrate data from SQL Server to OceanBase Database by using MySQL Workbench
  • SQL development
    • WebLogic
    • DBeaver
    • Navicat
    • DataGrip
    • TablePlus
    • DMS
  • Orchestration and scheduling
    • Airflow
    • PowerJob
    • DolphinScheduler
    • Linkis
  • Visualization tools
    • Superset
    • Excel
    • Power BI
    • Quick BI
    • Tableau
    • GuanData
    • vividime
    • DataV
    • Metabase
    • Redash
    • FineReport
  • Database management
    • NineData
    • Bytebase
    • DataHub
    • Zabbix
  • AI
    • OpenAI
    • Qwen
    • LangChain
    • LlamaIndex
    • Dify
    • n8n
    • Trae
    • SpringAI
    • Cline
    • Cursor
    • Continue
    • MCP Toolbox
    • CamelAI
    • Firecrawl
    • Hugging Face
    • Ollama
    • Google Gemini
    • Cloudflare Workers AI
    • DB GPT
    • Jina AI
    • Augment Code
    • Claude Code
    • Kiro
    • GPT4All
  • Application
    • Ghost
    • Jira
    • Seata
    • SAP Crystal Reports
  • Middleware
    • Apache Pulsar

Download PDF

Document Feedback
  1. Documentation Center
  2. OceanBase Database
  3. master

Connect to OceanBase Database in MySQL mode by using TypeORM

Last Updated:2026-09-04 07:40:45

Prerequisites
Procedure
Step 1: Check the versions of Node.js and npm
Step 2: Install the required dependencies
Step 3: Configure the project
Step 4: Data operation examples
Step 5: Run the sample
References

Applicability

TypeORM is applicable to OceanBase Database in MySQL mode.

TypeORM is an ORM framework that supports TypeScript and JavaScript. It supports multiple database systems. This topic describes how to connect to OceanBase Database in MySQL mode by using TypeORM.

Prerequisites

  • Node.js 14.0.0 or later is installed.
  • The npm or yarn package manager is installed.
  • OceanBase Database is deployed and a MySQL tenant is created.
  • A TypeScript environment is available (recommended).

Procedure

  1. Check the Node.js and npm versions.
  2. Install the required dependencies.
  3. Configure the project.
  4. Data operation example.
  5. Run the example.

Step 1: Check the versions of Node.js and npm

In the terminal, run the following command to check the versions of Node.js and npm:

node -v
npm -v

Step 2: Install the required dependencies

  1. Create a project directory and initialize it:

    mkdir typeorm-oceanbase-demo
    cd typeorm-oceanbase-demo
    npm init -y
    
  2. Install TypeORM and the MySQL2 driver:

    npm install typeorm mysql2 reflect-metadata
    
    # If you use TypeScript
    npm install --save-dev typescript @types/node
    
    # Initialize TypeScript configuration
    npx tsc --init
    
    
  3. Update tsconfig.json to support decorators:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "es6",
    "module": "commonjs",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

Step 3: Configure the project

  1. Create the project directory structure:

    mkdir -p src/entity src/migration src/subscriber
    
  2. Create the TypeORM configuration file ormconfig.json:

    {
      "type": "mysql",
      "host": "oceanbase-host",
      "port": 2881,
      "username": "your_username",
      "password": "your_password",
      "database": "your_database",
      "synchronize": true,
      "logging": false,
      "entities": ["src/entity/**/*.ts"],
      "migrations": ["src/migration/**/*.ts"],
      "subscribers": ["src/subscriber/**/*.ts"],
      "cli": {
        "entitiesDir": "src/entity",
        "migrationsDir": "src/migration",
        "subscribersDir": "src/subscriber"
      }
    }
    

Notice

  • Replace host, port, username, password, and database with your OceanBase Database connection information
  • If you use SSL connections, add the ssl: { rejectUnauthorized: false } configuration
  • Set synchronize to true during development, but use migrations in production to manage database schema changes
  • We recommend using a .env file and environment variables to store sensitive information

Step 4: Data operation examples

1. Define an entity

Create the src/entity/User.ts file:

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id?: number;

  @Column()
  firstName: string = "";

  @Column()
  lastName: string = "";

  @Column({ unique: true })
  email: string = "";

  @Column()
  age: number = 0;
}

2. Create a database connection and perform operations

Create the src/index.ts file:

import 'reflect-metadata';
import { createConnection } from 'typeorm';
import { User } from './entity/User';

async function main() {
  // 1. Create a database connection
  const connection = await createConnection();
  console.log('Database connection established');

  // 2. Create a new user
  const user = new User();
  user.firstName = "Zhang";
  user.lastName = "San";
  user.email = "zhangsan@example.com";
  user.age = 25;

  await connection.manager.save(user);
  console.log('User saved, User ID: ', user.id);

  // 3. Query all users
  const users = await connection.manager.find(User);
  console.log('All users: ', users);

  // 4. Query by conditions
  const specificUser = await connection.manager.findOne(User, {
    where: {
      firstName: "Zhang",
      lastName: "San"
    }
  });
  console.log('Query by conditions: ', specificUser);

  // 5. Use QueryBuilder for complex queries
  const userRepository = connection.getRepository(User);
  const queryBuilderUsers = await userRepository
    .createQueryBuilder("user")
    .where("user.age > :age", { age: 18 })
    .orderBy("user.age", "DESC")
    .getMany();
  console.log('Complex query: ', queryBuilderUsers);

  // 6. Update records
  await connection
    .createQueryBuilder()
    .update(User)
    .set({ firstName: "Li", lastName: "Si" })
    .where("id = :id", { id: 1 })
    .execute();
  const updateUsers = await connection.manager.find(User);
  console.log('Updated records: ', updateUsers);

  // 7. Delete records
  await connection
    .createQueryBuilder()
    .delete()
    .from(User)
    .where("id = :id", { id: 1 })
    .execute();
  const deleteUsers = await connection.manager.find(User);
  console.log('Deleted records: ', deleteUsers);
}

main().catch(error => {
  console.error('Error occurred:', error);
  process.exit(1);
});

Step 5: Run the sample

  1. Make sure that the database is running and accessible.

  2. Compile the TypeScript code:

    npx tsc
    
  3. Run the sample:

    node src/index.js
    

Note

In a real project, make sure that:

  • Passwords must be encrypted (for example, using bcrypt).
  • Errors that may occur are handled.
  • Database connection information is managed by using environment variables.
  • Appropriate input validation is added.

References

  • TypeORM official documentation
  • OceanBase Database documentation
  • TypeScript documentation
  • Node.js documentation

Previous topic

Sequelize
Last

Next topic

Prisma
Next
on this page
Prerequisites
Procedure
Step 1: Check the versions of Node.js and npm
Step 2: Install the required dependencies
Step 3: Configure the project
Step 4: Data operation examples
Step 5: Run the sample
References