Video in progress
How do the Repository and DAO patterns differ, and when you write only an interface in Spring Data, where does the implementation come from?
A DAO is a low-level CRUD layer close to the table. A Repository is a collection-like abstraction for domain objects (aggregates). At startup, Spring Data creates a JDK dynamic proxy for your interface, backed by SimpleJpaRepository and by queries derived from method names.
📖 Answer
The difference is mostly in intent. A DAO hides "working with a table": insertUser, updateUserEmail, findUsersByStatus, one method per query, and often one DAO per table. A Repository speaks the domain language: "the collection of orders". You take an aggregate out of it and put it back. There is no separate repository for OrderLine; it is saved through Order.
In Spring Data:
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByStatusAndCreatedAtAfter(OrderStatus s, Instant from);
}
At startup, Spring Data finds the interface and builds a proxy through the repository factory. If you log orderRepository.getClass(), you'll see jdk.proxy2.$Proxy.... Calls are split up like this:
- standard methods like
saveandfindByIdgo toSimpleJpaRepository; findBy...methods get JPQL built from their name, and if the name is wrong, the application fails at startup;@Queryis a query you write yourself.
If you need your own code, you add a fragment: an OrderRepositoryCustom interface and an OrderRepositoryCustomImpl class. Spring finds it by the Impl suffix and wires it into the proxy.
Practical advice: don't let every Spring Data repository turn into an automatic DAO for each entity. If you open a repository for every small entity, the aggregate boundary breaks, and someone bypasses the Order invariants with OrderLineRepository.save().
Sign up to mark studied questions and save your progress.