0Pricing
Java Academy · Lesson

Spring Data Repositories and Query Methods

Extend JpaRepository, define query methods by naming conventions, and use @Query for custom JPQL.

Spring Data Repositories and Query Methods is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Spring Data JPA Repositories

Extend JpaRepository<Entity, ID> to get CRUD, paging, and sorting methods for free. Spring generates the implementation at startup — no SQL or DAO boilerplate required.

public interface UserRepository extends JpaRepository<User, Long> {
    // Free: findAll, findById, save, delete, count, existsById, etc.
}

Derived Query Methods

Spring Data generates queries from method names. The naming convention follows: findBy + property + optional conditions.

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByStatus(UserStatus status);
    Optional<User> findByEmail(String email);
    List<User> findByAgeGreaterThanAndStatusOrderByNameAsc(int age, UserStatus s);
    boolean existsByEmail(String email);
    long countByStatus(UserStatus status);
}

Supported Keywords in Method Names

Key naming keywords: And, Or, Is/Equals, Between, LessThan/GreaterThan, Like/NotLike, In/NotIn, IsNull/IsNotNull, OrderBy, First/Top.

List<User> findTop5ByStatusOrderByCreatedAtDesc(UserStatus s);
List<User> findByNameContainingIgnoreCase(String fragment);
List<User> findByCreatedAtBetween(LocalDateTime from, LocalDateTime to);

@Query for Custom JPQL

Use @Query for complex queries that cannot be expressed as method names. JPQL uses entity class names and fields, not table/column names.

@Query("SELECT u FROM User u WHERE u.email = :email AND u.status = :status")
Optional<User> findActiveByEmail(@Param("email") String email,
                                @Param("status") UserStatus status);

@Query("SELECT u.name, COUNT(o) FROM User u JOIN u.orders o GROUP BY u.name")
List<Object[]> countOrdersPerUser();

Native Queries

Use nativeQuery = true to write raw SQL. Useful for database-specific features like ON CONFLICT, window functions, or full-text search.

@Query(value = "SELECT * FROM users WHERE tsv @@ plainto_tsquery(:q)",
       nativeQuery = true)
List<User> fullTextSearch(@Param("q") String query);

Modifying Queries with @Modifying

Annotate update/delete queries with @Modifying. Add @Transactional since modifying queries require an active transaction.

@Modifying
@Transactional
@Query("UPDATE User u SET u.status = :s WHERE u.lastLogin < :cutoff")
int deactivateInactiveUsers(@Param("s") UserStatus s,
                             @Param("cutoff") LocalDateTime cutoff);

Derived Delete Methods

Spring Data also generates delete queries from method names — convenient for cleanup operations.

void deleteByStatus(UserStatus status);
long deleteByCreatedAtBefore(LocalDateTime cutoff);

Repository Slices: CrudRepository, PagingAndSortingRepository

Use narrower base interfaces when you don't need all JpaRepository methods. CrudRepository has basic CRUD; PagingAndSortingRepository adds findAll(Pageable).

public interface ReadOnlyUserRepository extends PagingAndSortingRepository<User, Long> {
    // Only paging + sorting — no save/delete
}

@EntityGraph for Fetch Optimization

Use @EntityGraph to override the default fetch strategy per query, loading associations eagerly without changing the entity mapping.

@EntityGraph(attributePaths = {"orders", "orders.items"})
@Query("SELECT u FROM User u WHERE u.id = :id")
Optional<User> findWithOrders(@Param("id") Long id);

Custom Repository Implementations

Add a custom method by creating an interface + impl class with the naming convention UserRepositoryCustom + UserRepositoryCustomImpl. Spring merges them.

public interface UserRepositoryCustom {
    List<User> searchByCriteria(UserSearchCriteria criteria);
}
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
    @PersistenceContext EntityManager em;
    public List<User> searchByCriteria(UserSearchCriteria c) {
        // use Criteria API or JdbcTemplate
    }
}
public interface UserRepository extends JpaRepository<User,Long>, UserRepositoryCustom {}

Quick Check

What annotation is required alongside @Query for UPDATE/DELETE statements?

Recap

Extend JpaRepository for free CRUD. Use derived method names for simple queries. Use @Query for complex JPQL or native SQL. @Modifying+@Transactional for updates. @EntityGraph to tune fetching.

Frequently asked questions

Is the “Spring Data Repositories and Query Methods” lesson free?

Yes — the full text of “Spring Data Repositories and Query Methods” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Spring Data Repositories and Query Methods”?

Extend JpaRepository, define query methods by naming conventions, and use @Query for custom JPQL. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Spring Data Repositories and Query Methods” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Entity Mapping with JPA Annotations
  2. Spring Data Repositories and Query Methods
  3. One-to-Many and Many-to-Many Relationships
  4. Pagination, Sorting, and Projections
← Back to Java Academy