คำค้นหา JPQL และเนทีฟด้วย @Query
เขียนคำค้นหา JPQL และ SQL เนทีฟอย่างชัดเจน ผูกพารามิเตอร์แบบระบุชื่อและตามตำแหน่ง และแมปโพรเจกชัน
คำค้นหา JPQL และเนทีฟด้วย @Query เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why @Query Exists
Spring Data JPA can derive queries from method names like findByLastName, but derived queries break down for anything non-trivial: joins across entities, aggregations, custom projections, or fine-tuned SQL.
The @Query annotation lets you attach an explicit query to a repository method. You write the query once, declaratively, and Spring binds the method's parameters and maps the result.
- JPQL — object-oriented query language that works against entities and fields.
- Native SQL — raw database SQL when you need vendor features or hand-tuned queries.
A Basic JPQL @Query
JPQL looks like SQL but operates on entity names and Java field names, not table and column names. Here User is the entity class and email is a Java field.
Notice the placeholder ?1 — this is a positional parameter bound to the first method argument.
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.email = ?1")
Optional<User> findByEmailAddress(String email);
}Named Parameters with @Param
Positional parameters (?1, ?2) work, but they break when you reorder arguments. Named parameters are clearer and safer: write :name in the query and bind it with @Param("name").
- The string in
@Parammust match the:placeholderexactly. - Order of method arguments no longer matters.
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.status = :status AND u.age >= :minAge")
List<User> findActiveAdults(@Param("status") String status,
@Param("minAge") int minAge);
}Named vs Positional — Which to Use
Both styles bind method arguments into the query, but they differ in maintainability.
- Positional (
?1) — concise for one or two params; fragile when you add or reorder arguments. - Named (
:status) — self-documenting and resilient to refactoring; preferred for queries with multiple parameters.
The team standard in Spring Boot 4 projects is to favor named parameters for readability. Reserve positional parameters for very short queries.
Native SQL Queries
When you need database-specific SQL — window functions, vendor extensions, or a hand-optimized statement — set nativeQuery = true. Now the query runs as raw SQL against table and column names, not entity fields.
The result is still mapped back to the User entity because the selected columns match the entity's table.
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM users WHERE email = :email",
nativeQuery = true)
Optional<User> findByEmailNative(@Param("email") String email);
}JPQL vs Native — Picking the Right Tool
Default to JPQL; reach for native SQL only when JPQL can't express what you need.
- JPQL — portable across databases, refactor-safe (uses Java field names), integrates with the persistence context.
- Native — full SQL power and vendor features, but ties you to one database dialect and bypasses some JPA conveniences.
A common pitfall: in native queries LIKE wildcards and pagination must follow your database's SQL, not JPQL rules.
Interface-Based Projections
Often you don't need the whole entity — just a few columns. A projection returns a lightweight view instead of a full User.
Define an interface with getters; Spring matches each getter to a selected alias. This loads only the columns you ask for.
public interface UserSummary {
String getName();
String getEmail();
}
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u.name AS name, u.email AS email FROM User u WHERE u.active = true")
List<UserSummary> findActiveSummaries();
}Aliases Matter for Projections
For an interface projection to bind, each selected expression must be aliased to match the getter name. The getter getEmail() maps to alias email.
SELECT u.email AS emailbinds togetEmail().- Omitting the alias on a computed column leaves the getter unmapped and returns
null.
This holds for both JPQL and native projection queries.
DTO Projections with Constructor Expressions
JPQL also supports constructor expressions: build a DTO directly in the query with the NEW keyword. You must use the fully-qualified class name and match a constructor's parameter order.
This gives you an immutable, typed result object instead of an interface proxy.
public record UserDto(String name, String email) {}
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT new com.example.app.UserDto(u.name, u.email) FROM User u WHERE u.active = true")
List<UserDto> findActiveDtos();
}Modifying Queries
@Query can also run UPDATE and DELETE statements. These require @Modifying so Spring executes them as updates rather than selects, and they typically run inside a @Transactional method.
The return value is the count of affected rows.
public interface UserRepository extends JpaRepository<User, Long> {
@Modifying
@Transactional
@Query("UPDATE User u SET u.status = :status WHERE u.lastLogin < :cutoff")
int deactivateStale(@Param("status") String status,
@Param("cutoff") LocalDate cutoff);
}A Standalone JPQL Mental Model
JPQL parameter binding mirrors how you'd substitute values yourself. The snippet below is plain Java that demonstrates the named-parameter substitution idea behind :status and :minAge — no database required.
In real code Spring does this binding safely via prepared statements; this just illustrates the concept.
import java.util.Map;
public class ParamBindingDemo {
static String bind(String query, Map<String, String> params) {
for (Map.Entry<String, String> e : params.entrySet()) {
query = query.replace(":" + e.getKey(), e.getValue());
}
return query;
}
public static void main(String[] args) {
String jpql = "SELECT u FROM User u WHERE u.status = :status AND u.age >= :minAge";
Map<String, String> params = Map.of("status", "'ACTIVE'", "minAge", "18");
System.out.println(bind(jpql, params));
}
}Quick Check
Test your understanding of @Query parameter binding and projections.
Recap
You now know how to write explicit queries with @Query:
- JPQL works on entity and field names; native SQL (
nativeQuery = true) works on tables and columns. - Bind values with positional (
?1) or, preferably, named (:name+@Param) parameters. - Interface projections need aliases matching getter names; constructor expressions (
SELECT new ...) build typed DTOs. - Use
@Modifying(with@Transactional) forUPDATE/DELETEqueries.
Default to JPQL for portability; drop to native SQL only when you truly need database-specific power.
คำถามที่พบบ่อย
บทเรียน “คำค้นหา JPQL และเนทีฟด้วย @Query” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “คำค้นหา JPQL และเนทีฟด้วย @Query” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “คำค้นหา JPQL และเนทีฟด้วย @Query”
เขียนคำค้นหา JPQL และ SQL เนทีฟอย่างชัดเจน ผูกพารามิเตอร์แบบระบุชื่อและตามตำแหน่ง และแมปโพรเจกชัน คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “คำค้นหา JPQL และเนทีฟด้วย @Query” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม
ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- เมธอดคำค้นหาที่อนุมานและการแปลคีย์เวิร์ด
- คำค้นหา JPQL และเนทีฟด้วย @Query
- ข้อกำหนดและการกรองแบบไดนามิกตามเกณฑ์
- การแบ่งหน้า การเรียงลำดับ และการสตรีมสไลซ์