Usage with MySQL, MariaDB, PostgreSQL or SQLite
To use mikro-orm
with MySQL database, do not forget to install mysql2
dependency and set
the type option to mysql
when initializing ORM.
Similarly for SQLite install sqlite
dependency and provide sqlite
database type. For
PostgreSQL install pg
and provide postgresql
type.
Then call MikroORM.init
as part of bootstrapping your app:
#
Custom driverIf you want to use database that is not currently supported, you can implement your own driver.
More information about how to create one can be found here. Then provide the
driver class via driver
configuration option:
#
SchemaCurrently you will need to maintain the database schema yourself. For initial dump, you can
use SchemaGenerator
helper.
#
ManyToMany collections with pivot tablesAs opposed to MongoDriver
, in MySQL we use pivot tables to handle ManyToMany
relations:
You can adjust the name of pivot table via pivotTable
option in @ManyToMany
decorator
defined on owning side:
#
Using QueryBuilder to execute native SQL queriesWhen you need to execute some SQL query without all the ORM stuff involved, you can either
compose the query yourself, or use the QueryBuilder
helper to construct the query for you:
QueryBuilder
provides fluent interface with these methods:
For more examples of how to work with QueryBuilder
, take a look at QueryBuilder
tests in
tests/QueryBuilder.test.ts
.
#
TransactionsWhen you call em.flush()
, all computed changes are queried inside a database
transaction by default, so you do not have to handle transactions manually.
When you need to explicitly handle the transaction, you can use em.transactional(cb)
to run callback in transaction. It will provide forked EntityManager
as a parameter
with clear isolated identity map - please use that to make changes.
#
LIKE QueriesSQL supports LIKE queries via native JS regular expressions:
#
Native Collection MethodsSometimes you need to perform some bulk operation, or you just want to populate your
database with initial fixtures. Using ORM for such operations can bring unnecessary
boilerplate code. In this case, you can use one of nativeInsert/nativeUpdate/nativeDelete
methods:
Those methods execute native SQL queries generated via QueryBuilder
based on entity
metadata. Keep in mind that they do not hydrate results to entities, and they do not
trigger lifecycle hooks.
They are also available as EntityRepository
shortcuts:
Additionally there is execute()
method that supports executing raw SQL queries or QueryBuilder
instances. To create QueryBuilder
, you can use createQueryBuilder()
factory method on both
EntityManager
and EntityRepository
classes: