Home > Web Front-end > JS Tutorial > 9 Best JavaScript and TypeScript ORMs for 2024

9 Best JavaScript and TypeScript ORMs for 2024

Joseph Gordon-Levitt
Release: 2025-02-09 12:55:08
Original
822 people have browsed it

9 Best JavaScript and TypeScript ORMs for 2024

This article will briefly explain what is object-relational mapping (ORM), what is ORM library, and why you should consider using it in your next JavaScript project. We will also help you evaluate the best JavaScript and TypeScript ORM libraries based on your needs as a project developer and maintenance worker.

We will look at each of the following tools:

  • Knex.js: SQL query builder
  • Sequelize
  • Bookshelf
  • Waterline
  • Objection.js
  • Mongoose
  • Typegoose
  • TypeORM
  • MikroORM
  • Prisma

Object Relationship Map

Object relational mapping may seem complicated, but its purpose is to make your life easier as a programmer. To get data from the database, you need to write a query. But does this mean you have to learn SQL? No, object-relational mapping allows you to write queries in the language of your choice.

Object relational mapping is a technique that converts database query results into entity class instances. Entities are just object wrappers for database tables. It contains properties mapped to the database table column. Entity instances have methods to perform CRUD operations and support other features that include custom logic such as verification and data encryption.

If you are building a small project, you do not need to install the ORM library. It is enough to use SQL statements to drive your application. ORM is very beneficial for medium and large projects that get data from hundreds of database tables. In this case, you need a framework that allows you to operate and maintain the data layer of your application in a consistent and predictable way.

Entity classes are building blocks for business applications, as they are designed to encapsulate the logic used to implement business rules. Business rules are defined to ensure that automated processes are executed only within the scope of business policies. Examples of business rules include:

  • Customer Discount
  • Loan approval
  • Sales Commission
  • Shipping and tax calculation

ORM library

Object relational mapping is usually done with the help of libraries. The term ORM most often refers to the actual ORM library—Object Relationshipmapper—it does the work of object relations mapping for you.

Business rules usually require batch execution of multiple SQL statements. If a single SQL statement fails, it may leave the database in an inconsistent state. Most ORM libraries support a feature called transactions, which prevents such events from happening. If the SQL statement fails to run in this transaction context, all other SQL statements that have been successfully executed in that batch are undoped by an operation called rollback.

Therefore, using the ORM library to build your data layer helps ensure that the database is always consistent. The ORM library usually contains more basic functions, such as:

  • Query Builder
  • Migration script
  • CLI tool for generating boilerplate code
  • Sow function for pre-filling tables with test data

In this article, I will provide a snippet of code on how each ORM library does the following:

  • Initial Settings and Configuration
  • Basic CRUD operation
  • Advanced Query Operation

I also include important information such as the launch date, number of users, and document links, as well as the available support channels. I will also discuss the most important issues related to query performance, library maintenance, and architecture philosophy that you should carefully weigh when making your decisions.

I sorted the list by the start date from the earliest to the latest. I divided the list into two parts according to the main supported languages: JavaScript and TypeScript.

Before we start the evaluation, let's first look at Knex.js, a popular SQL query builder that has been integrated with many of the ORM libraries listed here. Knex.js is very flexible and generally performs better than some ORM libraries that have their own built-in implementation of query builders. Consider it an advantage when choosing an ORM library to use Knex.js as its basis.

Knex.js: SQL query builder

  • Start: December 2012
  • Website
  • GitHub: 158.6k Users
  • Databases: Postgres, MSSQL, MySQL, MariaDB, SQLite3, Oracle, and Amazon Redshift

Knex.js is currently the most mature JavaScript SQL query builder that can run in Node.js and in browsers (via webpack or Browserify). It is able to generate the same high-performance SQL queries as manually written SQL statements.

So what is a query builder?

It is just an API that provides a set of functions that can be linked together to form queries. Here is an example:

<code>knex({ a: 'table', b: 'table' })
  .select({
    aTitle: 'a.title',
    bTitle: 'b.title'
  })
  .whereRaw('?? = ??', ['a.column_1', 'b.column_2'])

SQL 输出:
select `a`.`title` as `aTitle`, `b`.`title` as `bTitle` from `table`
as `a`, `table` as `b` where `a`.`column_1` = `b`.`column_2`
</code>
Copy after login
Copy after login

This begs the question, why should you use a query builder instead of writing original SQL statements? I will give you four reasons:

  • It helps you abstract your code from the SQL dialect of your database, making it easier to switch.
  • It eliminates or greatly reduces the chance of SQL injection attacks on your application.
  • It allows easy construction of queries with dynamic conditions.
  • It has other functions and CLI tools for performing database development operations.

These functions include:

  • Connection Pool
  • Callback and Promise interface
  • Stream interface
  • Transaction Support
  • Mode support
  • Migration
  • Sow seeds

Installing it in your application requires you to install the Knex.js package and the driver for the database you are using:

<code>$ npm install knex --save

# 然后添加以下一个(添加 --save)标志:
$ npm install pg
$ npm install sqlite3
$ npm install mysql
$ npm install mysql2
$ npm install oracledb
$ npm install mssql
</code>
Copy after login
Copy after login

This is a setup code example:

<code>const knex = require('knex')({
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
});

knex.schema.createTable('users', function (table) {
  table.increments();
  table.string('name');
  table.timestamps();
})

输出:
create table `users` (`id` int unsigned not null auto_increment primary key, `name` varchar(255),
`created_at` datetime, `updated_at` datetime)
</code>
Copy after login
Copy after login

This is a basic query example:

<code>knex('users').where({
  first_name: 'Test',
  last_name:  'User'
}).select('id')

输出:
select `id` from `users` where `first_name` = 'Test' and `last_name` = 'User'
</code>
Copy after login
Copy after login

also supports raw SQL statements. Here is an example of a complex query:

<code>const subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no')
.wrap('(', ') avg_sal_dept');

knex.select('e.lastname', 'e.salary', subcolumn)
.from('employee as e')
.whereRaw('dept_no = e.dept_no')

输出:
select `e`.`lastname`, `e`.`salary`, (select avg(salary) from employee where dept_no = e.dept_no)
avg_sal_dept from `employee` as `e` where dept_no = e.dept_no
</code>
Copy after login
Copy after login

Knex.js also supports TypeScript, which is great because it allows you to write code like this:

<code>knex({ a: 'table', b: 'table' })
  .select({
    aTitle: 'a.title',
    bTitle: 'b.title'
  })
  .whereRaw('?? = ??', ['a.column_1', 'b.column_2'])

SQL 输出:
select `a`.`title` as `aTitle`, `b`.`title` as `bTitle` from `table`
as `a`, `table` as `b` where `a`.`column_1` = `b`.`column_2`
</code>
Copy after login
Copy after login

In the TypeScript example above, Knex.js almost acts as an ORM. However, no entity object instance is created. Instead, use interface definitions to create JavaScript objects with type-safe properties.

Note that many of the ORM libraries listed in this article use Knex.js in the background. These include:

  • Bookshelf
  • Objection.js
  • MikroORM

ORM libraries usually provide additional features on top of Knex.js. Let's take a look at them in the next section.

JavaScript ORM Library

In this category, all libraries listed here are written in JavaScript and can be run directly in Node.js. TypeScript support is provided through built-in types or @types/node definition packages. If you want top-notch support for your TypeScript project, you should skip to the TypeScript ORM library section.

In the data access layer, two popular architectural patterns are used:

  • Data Mapper
  • Activity Record

Using the data mapper pattern, the entity class is pure and contains only properties. CRUD operations and business rules are implemented in containers called repositories. Here is an example:

<code>$ npm install knex --save

# 然后添加以下一个(添加 --save)标志:
$ npm install pg
$ npm install sqlite3
$ npm install mysql
$ npm install mysql2
$ npm install oracledb
$ npm install mssql
</code>
Copy after login
Copy after login

The logic of CRUD operations and business rules is implemented in the entity class using active record mode. Here is a similar example that illustrates the above:

<code>const knex = require('knex')({
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
});

knex.schema.createTable('users', function (table) {
  table.increments();
  table.string('name');
  table.timestamps();
})

输出:
create table `users` (`id` int unsigned not null auto_increment primary key, `name` varchar(255),
`created_at` datetime, `updated_at` datetime)
</code>
Copy after login
Copy after login

Using either mode has its advantages and disadvantages. These patterns were named by Martin Fowler in his 2003 book Enterprise Application Architecture Patterns. If you want to learn more about this topic, you should check out this book. Most of the ORM libraries listed in this article support one or both modes.

Let's start paying attention to them now.

Sequelize

  • Start: July 2010
  • Website
  • GitHub: 726k Users
  • Slack
  • Databases: Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server

Sequelize is a very mature and popular Node.js ORM library with excellent documentation with well explained code examples. It supports many of the data layer features we have mentioned in previous libraries. Unlike Bookshelf, it has its own query builder that performs as well as Knex.js.

Installing the library is very simple, and the database driver is also very direct:

<code>knex('users').where({
  first_name: 'Test',
  last_name:  'User'
}).select('id')

输出:
select `id` from `users` where `first_name` = 'Test' and `last_name` = 'User'
</code>
Copy after login
Copy after login

The following is a setup code and examples of CRUD and basic query statements:

<code>const subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no')
.wrap('(', ') avg_sal_dept');

knex.select('e.lastname', 'e.salary', subcolumn)
.from('employee as e')
.whereRaw('dept_no = e.dept_no')

输出:
select `e`.`lastname`, `e`.`salary`, (select avg(salary) from employee where dept_no = e.dept_no)
avg_sal_dept from `employee` as `e` where dept_no = e.dept_no
</code>
Copy after login
Copy after login

The following is an example of how to write a complex query:

<code>import { Knex, knex } from 'knex'

interface User {
  id: number;
  age: number;
  name: string;
  active: boolean;
  departmentId: number;
}

const config: Knex.Config = {
  client: 'sqlite3',
  connection: {
    filename: './data.db',
  },
};

const knexInstance = knex(config);

try {
  const users = await knex<user>('users').select('id', 'age');
} catch (err) {
  // 错误处理
}
</user></code>
Copy after login

In the last complex query example, the SQL output is:

<code>const repository = connection.getRepository(User);.

const user = new User();
user.firstName = "Timber";
await repository.save(user);

const allUsers = await repository.find();
</code>
Copy after login

Sequelize supports raw SQL statements, which gives developers the flexibility to write complex and high-performance SQL statements. The results can also be mapped to the object entity instance. Here is an example:

<code>const user = new User();
user.firstName = "Timber";
await user.save();

const allUsers = await User.find();
</code>
Copy after login

The main disadvantage of Sequelize is that it slows down in development and problems pile up and are not solved. Fortunately, one maintainer announced that the library will get the attention it deserves starting in 2021. Note that all ORM library projects in this article are open source and they do require the help of developers to make it better.

The remaining part is similar to the input text. You can perform pseudo-originality in the same way, and while maintaining the consistency of the content, adjust the wording and sentence structure. Due to space limitations, this place will not be expanded. Please note that the image format remains the same.

The above is the detailed content of 9 Best JavaScript and TypeScript ORMs for 2024. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template