Introduction

Spring Data JPA is a game-changer when it comes to working with databases in Java. It allows you to perform CRUD operations and complex queries without writing boilerplate code. This cheat sheet will help you quickly recall the most essential Spring Data JPA annotations, methods, and techniques you’ll use every day.


Basic Setup

<!-- pom.xml -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>runtime</scope>
</dependency>
# application.yml
spring:
  datasource:
    url: jdbc:h2:mem:testdb
    username: sa
    password:
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

Entity Basics

@Entity
@Table(name = "users")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(nullable = false)
  private String name;

  @Column(unique = true)
  private String email;
}

Repository Basics

public interface UserRepository extends JpaRepository<User, Long> {
  // Custom method
  List<User> findByName(String name);
}
Method NameDescription
findAll()Get all records
findById(id)Find by primary key
save(entity)Insert or update
deleteById(id)Delete by ID
count()Count records
existsById(id)Check if exists

Custom Queries

@Query("SELECT u FROM User u WHERE u.email = :email")
User findByEmail(@Param("email") String email);
@Modifying
@Query("UPDATE User u SET u.name = :name WHERE u.id = :id")
void updateUserName(@Param("id") Long id, @Param("name") String name);
AnnotationUse
@QueryCustom JPQL query
@ModifyingFor update/delete queries
@TransactionalNeeded for modifying queries

Pagination & Sorting

Page<User> findAll(Pageable pageable);
List<User> findAll(Sort sort);
PageRequest.of(page, size, Sort.by("name").ascending());
ClassPurpose
PageableHandle pagination
SortSort results by fields
Page<T>Paginated result

Relationships

@OneToMany(mappedBy = "user")
private List<Order> orders;

@ManyToOne
@JoinColumn(name = "user_id")
private User user;

@OneToOne
@JoinColumn(name = "profile_id")
private Profile profile;

Pro Tips

  • Use @EntityListeners(AuditingEntityListener.class) with @CreatedDate and @LastModifiedDate for auditing.
  • Avoid fetch = FetchType.EAGER on large collections.
  • Use Specification<T> for dynamic search filters.
  • Combine @Query with native SQL by adding nativeQuery = true.

Conclusion

Spring Data JPA simplifies database interaction, making your code clean, readable, and powerful. This cheat sheet will help you become more efficient and focus more on business logic rather than boilerplate.