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:
@Entity()
export class User {
@PrimaryKey()
id!: number;
@Property()
name!: string;
@OneToOne(() => Address)
address?: Address;
@ManyToMany(() => Car)
cars = new Collection<Car>(this);
constructor(name: string) {
this.name = name;
}
}
Now to create new instance of the User
entity, we are forced to provide the name
:
const user = new User('John Doe'); // name is required to create new user instance
user.address = new Address('10 Downing Street'); // address is optional
Once your entities are loaded, make a number of synchronous actions on your entities,
then call 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.
const user = await em.findOneOrFail(User, 1, {
populate: ['cars', 'address.city'],
});
user.title = 'Mr.';
user.address.street = '10 Downing Street'; // address is 1:1 relation of Address entity
user.cars.getItems().forEach(car => car.forSale = true); // cars is 1:m collection of Car entities
const car = new Car('VW');
user.cars.add(car);
// now we can flush all changes done to managed entities
await 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" = case
when ("id" = 1) then true
when ("id" = 2) then true
when ("id" = 3) then true
else "for_sale" end
where "id" in (1, 2, 3)
insert into "car" ("brand", "owner") values ('VW', 1);
commit;
Identity Map
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
).
📖 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
- Express + MongoDB
- Nest + MySQL
- RealWorld example app (Nest + MySQL)
- Koa + SQLite
- GraphQL + PostgreSQL
- Inversify + PostgreSQL
- NextJS + MySQL
- Accounts.js REST and GraphQL authentication + SQLite
- Nest + Shopify + PostgreSQL + GraphQL
JavaScript Examples
Authors
👤 Martin Adámek
See also the list of contributors who participated in this project.