0Pricing
Spring Boot 4 Complete Guide · บทเรียน

เมธอดคำค้นหาที่อนุมานและการแปลคีย์เวิร์ด

สร้างคำค้นหาคลังข้อมูลที่ซับซ้อนจากชื่อเมธอดล้วน ๆ ด้วยไวยากรณ์คีย์เวิร์ดคุณสมบัติของ Spring Data

เมธอดคำค้นหาที่อนุมานและการแปลคีย์เวิร์ด เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What Are Derived Query Methods?

Spring Data JPA can generate a full SQL query just by reading the name of a repository method. You write the method signature, leave the body to the framework, and Spring parses the name into a query at startup.

  • No @Query annotation needed
  • No hand-written JPQL or SQL
  • The method name is the query specification

This is called a derived query method, because the query is derived from the method name.

public interface UserRepository extends JpaRepository<User, Long> {

    // Spring derives: SELECT u FROM User u WHERE u.email = ?1
    User findByEmail(String email);
}

The Subject and the Predicate

Every derived method name splits into two parts:

  • The subject (an introducer like findBy, readBy, queryBy, getBy) which tells Spring what action to perform.
  • The predicate (everything after By) which becomes the WHERE clause.

In findByLastName, find is the subject and LastName is the predicate that maps to the lastName entity property.

public interface CustomerRepository extends JpaRepository<Customer, Long> {

    List<Customer> findByLastName(String lastName);

    List<Customer> readByCity(String city);  // 'readBy' works too

    Customer getById(Long id);               // 'getBy' works too
}

Combining Conditions with And / Or

You chain multiple properties using the keywords And and Or. Each property name in the chain must match an entity field, and the method parameters are bound left-to-right in the same order they appear.

  • findByFirstNameAndLastName → WHERE first_name = ?1 AND last_name = ?2
  • findByCityOrCountry → WHERE city = ?1 OR country = ?2
public interface CustomerRepository extends JpaRepository<Customer, Long> {

    List<Customer> findByFirstNameAndLastName(String firstName, String lastName);

    List<Customer> findByCityOrCountry(String city, String country);
}

Comparison Keywords

Beyond equality, Spring Data understands a rich set of comparison keywords appended after the property name:

  • LessThan, LessThanEqual, GreaterThan, GreaterThanEqual
  • Between — needs two parameters
  • Before, After — handy for dates

The keyword binds to the property right before it, so findByAgeGreaterThan targets the age property.

public interface ProductRepository extends JpaRepository<Product, Long> {

    List<Product> findByPriceLessThan(BigDecimal max);

    List<Product> findByPriceBetween(BigDecimal low, BigDecimal high);

    List<Product> findByCreatedAtAfter(LocalDateTime since);
}

Null, True, and Boolean Keywords

Some keywords take no parameter at all because the condition is baked into the name:

  • IsNull / IsNotNull → IS NULL / IS NOT NULL
  • True / False → compares a boolean property to true/false

Notice that findByActiveTrue() has an empty parameter list — the value is fixed by the keyword.

public interface AccountRepository extends JpaRepository<Account, Long> {

    List<Account> findByDeletedAtIsNull();

    List<Account> findByActiveTrue();

    List<Account> findByActiveFalse();
}

String Matching Keywords

For text columns, Spring Data offers keywords that translate into LIKE patterns:

  • Like — you supply the wildcards (%) yourself
  • StartingWith — appends % automatically
  • EndingWith — prepends %
  • Containing — wraps the value in %value%
  • IgnoreCase — makes the comparison case-insensitive
public interface CustomerRepository extends JpaRepository<Customer, Long> {

    List<Customer> findByEmailContaining(String fragment);

    List<Customer> findByLastNameStartingWith(String prefix);

    List<Customer> findByLastNameIgnoreCase(String lastName);
}

Ordering Results with OrderBy

You can embed sorting directly in the method name using OrderBy followed by the property and a direction (Asc or Desc). It goes at the very end of the predicate.

  • findByLastNameOrderByFirstNameAsc
  • findByActiveTrueOrderByCreatedAtDesc

For dynamic sorting at call time, prefer passing a Sort parameter instead of hard-coding it in the name.

public interface CustomerRepository extends JpaRepository<Customer, Long> {

    List<Customer> findByLastNameOrderByFirstNameAsc(String lastName);

    // Dynamic sort, supplied by the caller
    List<Customer> findByCity(String city, Sort sort);
}

Limiting with First and Top

To restrict how many rows come back, add First or Top right after the subject. They are interchangeable, and an optional number sets the limit.

  • findFirstByOrderByCreatedAtDesc → the single newest row
  • findTop3ByCategory → at most 3 rows for that category

Combined with OrderBy this is the idiomatic way to fetch "the latest N" records.

public interface OrderRepository extends JpaRepository<Order, Long> {

    Order findFirstByCustomerIdOrderByPlacedAtDesc(Long customerId);

    List<Order> findTop5ByStatusOrderByPlacedAtDesc(String status);
}

Traversing Nested Properties

Derived queries can reach into related entities. If Order has a Customer and the customer has an address.city, you can write findByCustomerAddressCity.

Spring resolves the path greedily, splitting on camel-case humps. When a property name is itself ambiguous (e.g. a field literally named customerAddress), insert an underscore to make the boundary explicit: findByCustomer_AddressCity.

public interface OrderRepository extends JpaRepository<Order, Long> {

    // Order -> customer -> address -> city
    List<Order> findByCustomerAddressCity(String city);

    // Explicit traversal boundary with underscore
    List<Order> findByCustomer_AddressCity(String city);
}

Counting, Existence, and Deletion

The subject keyword controls the operation, not just selection. Beyond find, you can derive:

  • countBy... → returns a long
  • existsBy... → returns a boolean
  • deleteBy... / removeBy... → deletes matching rows (use with @Transactional)

The predicate grammar is identical; only the return type and the action change.

public interface UserRepository extends JpaRepository<User, Long> {

    long countByActiveTrue();

    boolean existsByEmail(String email);

    @Transactional
    long deleteByLastLoginBefore(LocalDateTime cutoff);
}

How Keyword Resolution Actually Works

At application startup, Spring Data parses each method name into a PartTree. For every segment it tries the longest matching property path first, then peels off trailing keywords.

  • It validates each property against the entity's metamodel — a typo like findByemaill fails fast with PropertyReferenceException.
  • Because parsing happens at startup, broken method names break the context immediately, not at first call.

This pure-Java example shows the same camel-case splitting idea the parser uses.

public class PartTreeDemo {
    public static void main(String[] args) {
        String predicate = "FirstNameAndLastName";
        String[] parts = predicate.split("And");
        for (String p : parts) {
            // Lower-case the first letter to get the property name
            String prop = Character.toLowerCase(p.charAt(0)) + p.substring(1);
            System.out.println("Property: " + prop);
        }
    }
}

Quick Check

You need a repository method that returns the 3 most recently placed orders for a given status, newest first. Which derived method name is correct?

Recap

You now know how to build queries straight from method names:

  • Subject (find/read/get/count/exists/delete) sets the operation; predicate after By becomes the WHERE clause.
  • Combine fields with And/Or; compare with LessThan, Between, After; match text with Containing, StartingWith, IgnoreCase.
  • Parameter-free keywords: IsNull, True, False.
  • Sort with OrderBy...Asc/Desc (or a Sort param); limit with First/Top[N].
  • Traverse relations (findByCustomerAddressCity, use _ to disambiguate).
  • Spring parses names into a PartTree at startup, so invalid property paths fail fast.

For very long or complex names, switch to @Query — readability beats cleverness.

คำถามที่พบบ่อย

บทเรียน “เมธอดคำค้นหาที่อนุมานและการแปลคีย์เวิร์ด” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “เมธอดคำค้นหาที่อนุมานและการแปลคีย์เวิร์ด” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “เมธอดคำค้นหาที่อนุมานและการแปลคีย์เวิร์ด”

สร้างคำค้นหาคลังข้อมูลที่ซับซ้อนจากชื่อเมธอดล้วน ๆ ด้วยไวยากรณ์คีย์เวิร์ดคุณสมบัติของ Spring Data คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “เมธอดคำค้นหาที่อนุมานและการแปลคีย์เวิร์ด” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เมธอดคำค้นหาที่อนุมานและการแปลคีย์เวิร์ด
  2. คำค้นหา JPQL และเนทีฟด้วย @Query
  3. ข้อกำหนดและการกรองแบบไดนามิกตามเกณฑ์
  4. การแบ่งหน้า การเรียงลำดับ และการสตรีมสไลซ์
← กลับไปที่ Spring Boot 4 Complete Guide