Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the different use cases for using QueryBuilder vs. Repository in TypeORM? [closed]

I'm building an API using NestJS with TypeORM. I've been querying a MySQL database using the TypeORM Repository API mostly because the NestJS Database documentation section provided an example using this.photoRepository.find(). As I get further along, I've noticed many of my exploratory search results recommending using the TypeORM QueryBuilder API for performance and flexibility reasons.

I'm getting the sense that the Repository approach is easier to use for simple needs and a great abstraction if I ever decide to switch my database framework. On the other hand, it also seems to me that QueryBuilder is more performant and customizable.

Could we outline the different use cases for QueryBuilder vs. Repository in TypeORM?

like image 650
Kyle Whitaker Avatar asked Nov 06 '19 02:11

Kyle Whitaker


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.

What is QueryBuilder?

Using Query Builder, you can search and filter database objects, select objects and columns, create relationships between objects, view formatted query results, and save queries with little or no SQL knowledge.


1 Answers

The QueryBuilder API is very powerful and closer to SQL than the Repository API, so anything that is more complex or more SQL driven is more easily done through it. It is your last "tool" before going raw SQL with QueryRunner that you probably don't want to use everytime (as it makes development and refactoring longer).

Even if the repository is easier to do, maybe you don't want your codebase to allow the 2 API to be used as it "splits" the code but it all depends on your team preferences.

The point where the repository API is more friendly is about fetching relations, as eager / lazy relations are parsed from the decorators and you don't have to specify "joins" whereas the QueryBuilder implies you explicit those or it will fetch only the main table (it ignores the decorators, SQL is first citizen).

Anyway, even if you decide to abandon the Repository API or the QueryBuilder API, I recommand strongly that your queries are always easily found in a dedicated class (like a custom repository or a dedicated service) so you don't end up maintaining queries everywhere in your codebase, refactoring data access is dangerous if not controlled. I personally find the "find" method too powerful on Repository API for instance and disallow such API use outside of a dedicated service / class / whatever you decide.

like image 77
zenbeni Avatar answered Sep 20 '22 17:09

zenbeni