🤔 Unit of What?
You might be asking: What the hell is Unit of Work and why should I care about it?
Unit of Work maintains a list of objects (entities) affected by a business transaction and coordinates the writing out of changes. (Martin Fowler)
Identity Map ensures that each object (entity) gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them. (Martin Fowler)
So what benefits does it bring to us?
First and most important implication of having Unit of Work is that it allows handling transactions automatically.
When you call
em.flush(), all computed changes are queried inside a database
transaction (if supported by given driver). This means that you can control the boundaries
of transactions simply by calling
em.persistLater() and once all your changes
are ready, calling
flush() will run them inside a transaction.
You can also control the transaction boundaries manually via
;user.email = 'email@example.com';;user.cars.addcar;// thanks to bi-directional cascading we only need to persist user entity// flushing will create a transaction, insert new car and update user with new email// as user entity is managed, calling flush() is enoughawait em.flush;
ChangeSet based persistence
MikroORM allows you to implement your domain/business logic directly in the entities.
To maintain always valid entities, you can use constructors to mark required properties.
Let's define the
User entity used in previous example:
Now to create new instance of the
User entity, we are forced to provide the
; // name is required to create new user instanceuser.address = new Address'10 Downing Street'; // address is optional
Once your entities are loaded, make a number of synchronous actions on your entities,
em.flush(). This will trigger computing of change sets. Only entities
(and properties) that were changed will generate database queries, if there are no changes,
no transaction will be started.
;user.title = 'Mr.';user.address.street = '10 Downing Street'; // address is 1:1 relation of Address entityuser.cars.getItems.forEachcar.forSale = true; // cars is 1:m collection of Car entities;user.cars.addcar;// now we can flush all changes done to managed entitiesawait em.flush;
em.flush() will then execute these queries from the example above:
begin;update user set title = 'Mr.' where id = 1;update user_address set street = '10 Downing Street' where id = 123;update car set for_sale = true where id = 1;update car set for_sale = true where id = 2;update car set for_sale = true where id = 3;insert into car (brand, owner) values ('VW', 1);commit;
Only One Instance of Entity
Thanks to Identity Map, you will always have only one instance of given entity in one context.
This allows for some optimizations (skipping loading of already loaded entities), as well as
comparison by identity (
ent1 === ent2).
There is also auto-generated CHANGELOG.md file based on commit messages
You can browse MikroORM v3 docs at https://mikro-orm.io/docs/3.6/installation.
To upgrade to v4, please see the upgrading guide.
✨ Core Features
- Clean and Simple Entity Definition
- Identity Map
- Entity References
- Using Entity Constructors
- Modelling Relationships
- Unit of Work
- Cascading persist and remove
- Composite and Foreign Keys as Primary Key
- Preloading Deeply Nested Structures via populate
- Property Validation
- Lifecycle Hooks
- Vanilla JS Support
- Schema Generator
- Entity Generator
📦 Example Integrations
You can find example integrations for some popular frameworks in the
- Express + MongoDB
- Nest + MySQL
- RealWorld example app (Nest + MySQL)
- Koa + SQLite
- GraphQL + PostgreSQL
- Inversify + PostgreSQL
- Introducing MikroORM, TypeScript data-mapper ORM with Identity Map
- Handling transactions and concurrency in MikroORM
- MikroORM 3: Knex.js, CLI, Schema Updates, Entity Generator and more…
🚀 Quick Start
First install the module via
npm and do not forget to install the database driver as well:
Since v4, you should install the driver package, but not the db connector itself, e.g. install
@mikro-orm/sqlite, but not
sqlite3as that is already included in the driver package.
yarn add @mikro-orm/core @mikro-orm/mongodb # for mongoyarn add @mikro-orm/core @mikro-orm/mysql # for mysql/mariadbyarn add @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadbyarn add @mikro-orm/core @mikro-orm/postgresql # for postgresqlyarn add @mikro-orm/core @mikro-orm/sqlite # for sqlite
npm i -s @mikro-orm/core @mikro-orm/mongodb # for mongonpm i -s @mikro-orm/core @mikro-orm/mysql # for mysql/mariadbnpm i -s @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadbnpm i -s @mikro-orm/core @mikro-orm/postgresql # for postgresqlnpm i -s @mikro-orm/core @mikro-orm/sqlite # for sqlite
Next you will need to enable support for decorators
as well as
"experimentalDecorators": true,"emitDecoratorMetadata": true,"esModuleInterop": true,
MikroORM.init as part of bootstrapping your app:
;console.logorm.em; // access EntityManager via `em` property
There are more ways to configure your entities, take a look at installation page.
Read more about all the possible configuration options in Advanced Configuration section.
Then you will need to fork entity manager for each request so their
identity maps will not collide.
To do so, use the
You should register this middleware as the last one just before request handlers and before any of your custom middleware that is using the ORM. There might be issues when you register it before request processing middleware like
bodyParser, so definitely register the context after them.
More info about
RequestContext is described here.
Now you can start defining your entities (in one of the
entities folders). This is how
simple entity can look like in mongo driver:
For SQL drivers, you can use
id: number PK:
Or if you want to use UUID primary keys:
More information can be found in defining entities section in docs.
When you have your entities defined, you can start using ORM either via
To save entity state to database, you need to persist it. Persist takes care or deciding
whether to use
update and computes appropriate change-set. Entity references
that are not persisted yet (does not have identifier) will be cascade persisted automatically.
// use constructors in your entities for required parameters;author.born = new Date;;;book1.publisher = publisher;;book2.publisher = publisher;;book3.publisher = publisher;// just persist books, author and publisher will be automatically cascade persistedawait orm.em.persistAndFlush;
To fetch entities from database you can use
;for of authors
More convenient way of fetching entities from database is by using
carries the entity name so you do not have to pass it to every
;// with sorting, limit and offset parameters, populating author references;// or with options object;console.logbooks; // Book
Contributions, issues and feature requests are welcome. Please read CONTRIBUTING.md for details on the process for submitting pull requests to us.
👤 Martin Adámek
See also the list of contributors who participated in this project.
Show Your Support
Please ⭐️ this repository if this project helped you!
Copyright © 2018 Martin Adámek.
This project is licensed under the MIT License - see the LICENSE file for details.