# Repository Pattern

> One class that hides how a kind of data is read and saved.

**Field:** Software Development  
**Category:** Architecture  
**Also known as:** Repository Design Pattern, Repository Layer

## Think of it like

It is like a library desk. You ask for a book, and the librarian knows which shelf it is on.

## Definition

The repository pattern puts all the code that reads and saves one kind of data behind one class. Your app asks it for things, like find a user by email or save this order. Only the repository knows the database tables and queries. The rest of the code works with plain objects. In tests, you can swap the real repository for a fake one.

## Example

Jack's app asks the user repository to find a user by email. In tests, a fake one gives back users from a list. No database is needed.

## Example code

```python
class UserRepository:
    def find_by_email(self, email):
        row = self.db.query_one("SELECT * FROM users WHERE email = %s", email)
        return User(**row) if row else None
```

Only the repository knows the SQL. The app gets a User object back.

## Why it matters

Database code stays in one place, so a change of table or database touches little else. Tests run fast without a real database.

## Common mistake

Adding a repository on top of an ORM that already does that job. Two layers for one task add code but no value.

## Three principles

- **One kind of data.** One repository each.
- **Hides the database.** Plain objects come out.
- **Easy to fake.** Tests need no database.

## Related terms

- [Design Pattern](https://learn.benibix.com/term/development/design-pattern)
- [Object-Relational Mapping (ORM)](https://learn.benibix.com/term/development/orm)
- [Domain-Driven Design (DDD)](https://learn.benibix.com/term/development/domain-driven-design)
- [Dependency Injection](https://learn.benibix.com/term/development/dependency-injection)
- [Layered Architecture](https://learn.benibix.com/term/development/layered-architecture)
- [Database](https://learn.benibix.com/term/development/database)

![Four small panels. Decorator: a reader box wrapped inside a cache layer, wrapped inside a log layer, all with the same read method. Builder: three steps, url, header and timeout, then build, making one finished request. Facade: one place order box in front of three parts, stock, payment and shipping. Repository: app code asks a user repository for a user, and only the repository talks to the database.](https://learn.benibix.com/diagrams/dev6-more-patterns.svg)

---

Source: https://learn.benibix.com/term/development/repository-pattern
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-18
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
