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

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


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.