Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between entity manager and repository typeorm

I don't understand the differences between Entity manager and Repository in typeorm. They seem to do the same thing. If it's the same, why two different API exists. If not what are the differences and when we use them.

like image 560
BigLOL Avatar asked Apr 17 '20 14:04

BigLOL


People also ask

What is repository in Typeorm?

Repository is specific to an entity. In other words, each entity will have its own, build-in repository and it can be accessed using getRepository() method of connection object as specified below − const studRepository = manager. getRepository(Student);

What is EntityManager typeorm?

Advertisements. EntityManager is similar to Repository and used to manage database operations such as insert, update, delete and load data. While Repository handles single entity, EntityManager is common to all entities and able to do operations on all entities.


2 Answers

An Entity Manager handles all entities, while Repository handles a single entity. This means that when using an Entity Manager you have to specify the Entity you are working with for each method call.

Here is an example of a create method from the Entity Manager and Repository documentation for comparison:

const manager = getManager();
// ...
const user = manager.create(User); // same as const user = new User();

const repository = connection.getRepository(User);
// ...
const user = repository.create(); // same as const user = new User();

Both are valid and you can choose whichever you prefer to work with.

like image 180
Riley Conrardy Avatar answered Oct 22 '22 20:10

Riley Conrardy


It does exactly the same thing just an alias

either you do

Option 1:

const manager = getManager();
manager.find(Methodology);
manager.find(Infrastructure);
manager.find(Safety);

Option 2:

getRepository(Methodology).find();
getRepository(Infrastructure).find();
getRepository(Safety).find();
like image 27
Keyur Lakhani Avatar answered Oct 22 '22 21:10

Keyur Lakhani