Repositories
Repositories are your gateway to the database. Instead of writing SQL queries yourself, you define an interface and Spring Data JPA does all the heavy lifting. It's like having a personal assistant who handles all your database errands.
You create a repository interface for each entity. For a User entity, you'd create a UserRepository. Spring Data JPA will automatically generate the implementation at runtime. No manual coding needed.
Extending JpaRepository
The magic happens when you extend JpaRepository. This interface gives you a ton of useful methods out of the box. Save, delete, find by ID, find all, count, and more. All for free.
JpaRepository takes two type parameters: the entity type and the ID type. So for a User entity with Long IDs, you'd extend JpaRepository<User, Long>. That's it. You now have a fully functional repository.
public interface UserRepository extends JpaRepository<User, Long> {
}
CRUD Methods
Once you extend JpaRepository, you inherit all the standard CRUD methods. save() creates or updates. findById() gets a single record. findAll() returns everything. deleteById() removes a record.
You can call these methods directly from your service layer. No SQL, no boilerplate, just clean Java code that does exactly what you need.
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User saveUser(User user) {
return userRepository.save(user);
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
Custom Query Methods
Spring Data JPA goes beyond basic CRUD. You can define custom query methods just by writing a method name. Spring parses the name and generates the query for you. It's almost magical.
For example, if you need to find a user by email, just add findByEmail(String email) to your repository. Spring Data JPA figures out the rest. No need to write any SQL or JPQL.
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
List<User> findByName(String name);
boolean existsByEmail(String email);
}
Try it Yourself โ