MIT License

项目介绍

mikro-orm/mikro-orm 是一个托管在 GitHub 上的开源项目,主要使用 TypeScript 编写,采用 MIT License 许可证,目前获得 9.3k 个 Star、701 次 Fork。

仓库全名
mikro-orm/mikro-orm
开源许可证
MIT License
Star 数
9.3k
Fork 数
701
未关闭 Issue
13

README 摘要

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL (including CockroachDB and PGlite), SQLite (including libSQL), MSSQL and Oracle databases. Heavily inspired by Doctrine and Hibernate. Quick Start Install a driver package for your database: If you use additional packages like @mikro-orm/cli, @mikro-orm/migrations, or…

完整内容见 GitHub 原始 README 或本页 。

常见问题

mikro-orm 用什么语言开发?

主要使用 TypeScript 编写,采用 MIT License 许可证,目前有 9.3k 个 Star。

mikro-orm 可以免费商用吗?

仓库采用 MIT License 许可证,可免费使用与修改,商业使用请遵守许可证条款(例如保留版权声明与许可声明)。

如何获取 mikro-orm 的源码?

可以直接克隆仓库:git clone https://github.com/mikro-orm/mikro-orm.git,默认分支为 master;安装与运行步骤见仓库 README。

mikro-orm 最近还在维护吗?

仓库最近一次更新为 16 小时前,当前有 13 个未关闭 Issue;Star 数为 9.3k,可作为社区活跃度的参考。

README

MikroORM

TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL (including CockroachDB and PGlite), SQLite (including libSQL), MSSQL and Oracle databases.

Heavily inspired by Doctrine and Hibernate.

NPM version NPM dev version Chat on discord Downloads Coverage Status Build Status

Quick Start

Install a driver package for your database:

npm install @mikro-orm/postgresql   # PostgreSQL
npm install @mikro-orm/pglite       # PGlite (embedded PostgreSQL in WASM)
npm install @mikro-orm/mysql        # MySQL
npm install @mikro-orm/mariadb      # MariaDB
npm install @mikro-orm/sqlite       # SQLite
npm install @mikro-orm/libsql       # libSQL / Turso
npm install @mikro-orm/sql-js       # sql.js (in-memory SQLite in WASM)
npm install @mikro-orm/mongodb      # MongoDB
npm install @mikro-orm/mssql        # MS SQL Server
npm install @mikro-orm/oracledb     # Oracle

If you use additional packages like @mikro-orm/cli, @mikro-orm/migrations, or @mikro-orm/entity-generator, install @mikro-orm/core explicitly as well. See the quick start guide for details.

Define Entities

The recommended way to define entities is using defineEntity with setClass:

import { defineEntity, p, MikroORM } from '@mikro-orm/postgresql';

const AuthorSchema = defineEntity({
  name: 'Author',
  properties: {
    id: p.integer().primary(),
    name: p.string(),
    email: p.string(),
    born: p.datetime().nullable(),
    books: () => p.oneToMany(Book).mappedBy('author'),
  },
});

export class Author extends AuthorSchema.class {}
AuthorSchema.setClass(Author);

const BookSchema = defineEntity({
  name: 'Book',
  properties: {
    id: p.integer().primary(),
    title: p.string(),
    author: () => p.manyToOne(Author).inversedBy('books'),
  },
});

export class Book extends BookSchema.class {}
BookSchema.setClass(Book);

You can also define entities using decorators or EntitySchema. See the defining entities guide for all options.

Initialize and Use

import { MikroORM, RequestContext } from '@mikro-orm/postgresql';

const orm = await MikroORM.init({
  entities: [Author, Book],
  dbName: 'my-db',
});

// Create new entities
const author = orm.em.create(Author, {
  name: 'Jon Snow',
  email: '[email protected]',
});
const book = orm.em.create(Book, {
  title: 'My Life on The Wall',
  author,
});

// Flush persists all tracked changes in a single transaction
await orm.em.flush();

Querying

// Find with relations
const authors = await orm.em.findAll(Author, {
  populate: ['books'],
  orderBy: { name: 'asc' },
});

// Type-safe QueryBuilder
const qb = orm.em.createQueryBuilder(Author);
const result = await qb
  .select('*')
  .where({ books: { title: { $like: '%Wall%' } } })
  .getResult();

Request Context

In web applications, use RequestContext to isolate the identity map per request:

const app = express();

app.use((req, res, next) => {
  RequestContext.create(orm.em, next);
});

More info about RequestContext is described here.

Unit of Work

Unit of Work maintains a list of objects (entities) affected by a business transaction and coordinates the writing out of changes. (Martin Fowler)

When you call em.flush(), all computed changes are queried inside a database transaction. This means you can control transaction boundaries simply by making changes to your entities and calling flush() when ready.

const author = await em.findOneOrFail(Author, 1, {
  populate: ['books'],
});
author.name = 'Jon Snow II';
author.books.getItems().forEach(book => book.title += ' (2nd ed.)');
author.books.add(orm.em.create(Book, { title: 'New Book', author }));

// Flush computes change sets and executes them in a single transaction
await em.flush();

The above flush will execute:

begin;
update "author" set "name" = 'Jon Snow II' where "id" = 1;
update "book"
  set "title" = case
    when ("id" = 1) then 'My Life on The Wall (2nd ed.)'
    when ("id" = 2) then 'Another Book (2nd ed.)'
    else "title" end
  where "id" in (1, 2);
insert into "book" ("title", "author_id") values ('New Book', 1);
commit;

Core Features

Documentation

MikroORM documentation, included in this repo in the root directory, is built with Docusaurus and publicly hosted on GitHub Pages at https://mikro-orm.io.

There is also auto-generated CHANGELOG.md file based on commit messages (via semantic-release).

Example Integrations

You can find example integrations for some popular frameworks in the mikro-orm-examples repository:

TypeScript Examples

JavaScript Examples

Contributing

Contributions, issues and feature requests are welcome. Please read CONTRIBUTING.md for details on the process for submitting pull requests to us.

Authors

Martin Adámek

See also the list of contributors who participated in this project.

Show Your Support

Please star this repository if this project helped you!

If you’d like to support my open-source work, consider sponsoring me directly at github.com/sponsors/b4nan.

License

Copyright © 2018-present Martin Adámek.

This project is licensed under the MIT License - see the LICENSE file for details.

评论

暂无评论