Hackforge Academy

Category: java

Spring Data JPA

Published on 22 Apr 2026

Explanation

Spring Data JPA provides built-in query methods based on method naming conventions. Example: find user by name without writing SQL manually.

Code:

public interface UserRepository extends
 JpaRepository<User, Long> {
  User findByName(String name);
}

Explanation

You can create queries using multiple conditions by combining keywords like And, Or, Between, LessThan, GreaterThan.

Code:

List<User> findByNameAndAge(
String name, int age
);

Explanation

Use @Query annotation to write custom JPQL (Java Persistence Query Language) queries when method naming is not sufficient.

Code:

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

Explanation

JPQL works with entity class names and field names instead of table names and column names.

Code:

@Query("SELECT u FROM User u WHERE u.age >
 :age")
List<User> findUsersOlderThan(@Param("age")
 int age);

Explanation

You can write native SQL queries using nativeQuery = true when database-specific queries are required.

Code:

@Query(value = "SELECT * FROM users 
WHERE age > ?1", nativeQuery = true)
List<User> findUsersByAge(int age);

Explanation

Use positional parameters (?1, ?2) or named parameters (:name) while writing custom queries.

Code:

@Query("SELECT u FROM User u WHERE 
u.name = :name AND u.age = :age")
User findUser(@Param("name") 
String name, @Param("age") int age);

Explanation

Custom update or delete queries require @Modifying and @Transactional annotations.

Code:

@Modifying
@Transactional
@Query("UPDATE User u SET u.name 
= :name WHERE u.id = :id")

int updateUserName(@Param("id") 
Long id, @Param("name") String name);

πŸš€ 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