Hackforge Academy

Category: java

what is jpa query

Published on 19 May 2026

Explanation

JPA Query is used to communicate with the database in Java applications using JPA (Java Persistence API). It helps to fetch, insert, update, and delete data.

Code:

@Repository
public interface UserRepository extends 
JpaRepository<User, Long> {

}

Explanation

Method Name Query automatically generates SQL queries based on the method name.

Code:

List<User> findByName(String name);

Explanation

JPQL Query uses entity class names and entity fields instead of database table names.

Code:

@Query("SELECT u FROM User u")
List<User> getAllUsers();

Explanation

Fetch a user using email with JPQL query.

Code:

@Query("SELECT u FROM User u WHERE 
u.email = :email")
User findByEmail(@Param("email") 
String email);

Explanation

Native Query uses actual SQL queries directly.

Code:

@Query(value = "SELECT * FROM users",
 nativeQuery = true)
List<User> getUsers();

Explanation

Insert operation is usually done using save() method provided by JpaRepository.

Code:

userRepository.save(user);

Explanation

Update query in JPA requires @Modifying and @Transactional annotations.

Code:

@Modifying
@Transactional
@Query("UPDATE User u SET u.name = :name 
WHERE u.id = :id")
void updateName(@Param("id") Long id, 
@Param("name") String name);

Explanation

Delete query removes records from the database using JPQL.

Code:

@Modifying
@Transactional
@Query("DELETE FROM User u WHERE u.id = :id")
void deleteUser(@Param("id") Long id);

Explanation

Sorting can be done using ORDER BY in JPQL query.

Code:

@Query("SELECT u FROM User u 
ORDER BY u.name ASC")
List<User> getUsersSorted();

Explanation

LIKE operator is used for searching records with partial matching.

Code:

@Query("SELECT u FROM User u WHERE u.name 
LIKE %:keyword%")
List<User> searchUsers(@Param("keyword") 
String keyword);

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community