9.3 JpaRepository and Basic CRUD
After completing entity mapping, let me introduce JpaRepository, an interface that magically allows you to perform CRUD (Create, Read, Update, Delete) operations with these entities against the database.
Extending the JpaRepository Interface
Developers merely need to declare an interface that extends the JpaRepository<Entity Type, PK Type> interface supplied by Spring Data JPA.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
// NOTE: It is an interface, not a class.
@Repository // This annotation can be omitted.
public interface UserRepository extends JpaRepository<User, Long> {
}
With just this short code snippet, Spring automatically creates an implementation object (proxy object) for this interface at runtime and registers it as a Spring Bean. Consequently, you can readily inject and use this UserRepository within the Service Layer.
utilizing Basic CRUD Methods
By extending JpaRepository, you gain access to an incredible suite of methods right out of the box. You don't need any SQL knowledge for these operations!
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
public void testCrud() {
// [C]reate & [U]pdate (save: executes INSERT if no primary key exists, otherwise UPDATE)
User newUser = new User("admin@test.com", "1234", "admin");
userRepository.save(newUser);
// [R]ead Single entity (findById: searches based on PK, returns Optional)
Optional<User> foundUser = userRepository.findById(1L);
// [R]ead All Entities (findAll: retrieves all data)
List<User> userList = userRepository.findAll();
// [D]elete (delete: removes a record based on an entity or PK)
userRepository.deleteById(1L);
}
}
At runtime, these methods are translated into highly optimized SQL commands (e.g., SELECT * FROM users WHERE id = ?) and are then executed.
Query Methods
In addition to those primary methods, there's a phenomenal feature where merely adhering to a naming convention for your methods essentially translates the method's name into a query!
List<User> findByEmail(String email): Finds users whoseemailfield matches the provided parameter.List<User> findByNicknameContaining(String keyword): Matches entities wherenicknameincludes a specific keyword (functioning like a SQLLIKE).boolean existsByEmail(String email): Executes an extraordinarily efficientSELECT COUNTquery perfect for checking duplicate emails.
Because of this intuitive and striking pattern, backend development productivity soars enormously.