Spring Boot + JPA Basics for Freshers (Complete Beginner Guide)

Spring Boot + JPA Basics for Freshers (Complete Beginner Guide)

For freshers and junior developers, Spring Boot + JPA is one of the most heavily tested topics in technical interviews. This guide explains everything from scratch — not just how to write the code, but why things exist and how they work together under the hood.

What you will learn:
  • The exact difference between JPA and Hibernate.
  • How to map Entities correctly in Spring Boot 3 (Jakarta EE).
  • How Repositories automate CRUD operations.
  • How to write a complete API flow (Controller → Service → Repository).
  • Common fresher mistakes that fail interviews.

1️⃣ What Is JPA? (Explain This Clearly in Interviews)

JPA (Java Persistence API) is a specification. It is just a set of rules and interfaces that define how Java objects should be stored and retrieved from a relational database.

Because JPA is just a specification, it cannot perform database operations on its own. It requires an implementation engine like Hibernate to do the actual SQL generation and database work.

TermMeaningAnalogy
JPASpecification (rules & interfaces)The concept of a "Car"
HibernateImplementation (the engine)A physical "Honda Civic"
Spring Data JPASpring's abstraction layer over JPAAn automatic driver for the car
💡 Interview Tip: If an interviewer asks "Do you use JPA or Hibernate?", the correct answer is: "I use Spring Data JPA, which uses Hibernate internally as its default implementation provider."

2️⃣ Why Use JPA Instead of JDBC?

Without JPA, developers using raw JDBC must write:

  • Complex, database-specific SQL queries.
  • Tedious ResultSet mapping to manually convert database rows into Java objects.
  • Manual connection opening and closing (prone to memory leaks).

JPA removes this boilerplate by automatically mapping your Java Classes directly to Database Tables. This concept is known as ORM (Object-Relational Mapping).


3️⃣ Spring Boot + JPA Architecture

A professional Spring Boot application follows a strict 3-tier architecture:

Client Request → Controller → Service → Repository → Hibernate → Database
  • Controller: Handles the HTTP requests and JSON responses.
  • Service: Contains the business logic and @Transactional boundaries.
  • Repository: Contains the Spring Data JPA interfaces for database access.
💡 Interview Tip: Freshers often inject Repositories directly into Controllers to save time. Interviewers hate this. Always use a Service layer to separate your business logic from HTTP routing.

4️⃣ What Is an Entity? (Spring Boot 3 Updates)

An Entity is a standard Java class that represents a single table in your database. Every instance (object) of this class represents one row in that table.

Note: In Spring Boot 3, Java EE was migrated to Jakarta EE. Always ensure your imports say jakarta.persistence, not javax.persistence!

import jakarta.persistence.*;

@Entity
@Table(name = "users") // Maps this class to the 'users' table in the database
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY) // Tells DB to auto-increment this ID
  private Long id;

  @Column(nullable = false)
  private String name;
  
  @Column(unique = true)
  private String email;
  
  // Getters and Setters omitted for brevity
}

5️⃣ Repository Layer Explained Simply

Spring Data JPA provides repository interfaces so you don’t have to write basic SQL queries. You simply create an interface and extend JpaRepository.

import org.springframework.data.jpa.repository.JpaRepository;

// User = The Entity Type. Long = The Primary Key Type.
public interface UserRepository extends JpaRepository<User, Long> {
    
    // Spring automatically generates the SQL for this based on the method name!
    User findByEmail(String email);
}

By extending JpaRepository, you instantly get access to methods like save(), findById(), findAll(), and deleteById() without writing a single line of implementation code.


6️⃣ application.properties Configuration

To connect Spring Boot to your database (e.g., MySQL), you configure the application.properties file:

spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=secret

# Hibernate Configuration
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

Understanding ddl-auto values:

  • create – Drops the existing tables and creates new ones every time the app starts.
  • update – Updates the database schema if your Java Entity changes.
  • validate – Only checks if the schema matches your Java Entity. Does not make changes.
  • none – Does nothing. (Standard for Production).

7️⃣ Basic CRUD Flow (End-to-End Example)

Here is how the Controller and Service work together to save a new User.

The Service Layer:

@Service
public class UserService {

  private final UserRepository userRepository;

  public UserService(UserRepository userRepository) {
    this.userRepository = userRepository;
  }

  public User createUser(User user) {
    // Business logic goes here (e.g., checking if email already exists)
    return userRepository.save(user);
  }
}

The Controller Layer:

@RestController
@RequestMapping("/api/users")
public class UserController {

  private final UserService userService;

  public UserController(UserService userService) {
    this.userService = userService;
  }

  @PostMapping
  public ResponseEntity<User> create(@RequestBody User user) {
    User savedUser = userService.createUser(user);
    return ResponseEntity.ok(savedUser);
  }
}

8️⃣ Common Fresher Mistakes (Interview Gold)

  • Returning Entities directly from APIs: You should map Entities to DTOs (Data Transfer Objects) before returning them in the Controller. Returning Entities directly can cause infinite recursion (StackOverflow errors) if there are bidirectional relationships.
  • Forgetting a No-Args Constructor: Hibernate requires a default, empty constructor to instantiate objects via reflection. If you use parameterized constructors, ensure you also provide a default one (or use Lombok's @NoArgsConstructor).
  • Using EAGER fetching everywhere: By default, one-to-many relationships should be LAZY to prevent fetching massive amounts of unnecessary data from the database.

📺 Watch Spring Boot Architecture Built Live!
Watch step-by-step implementations of Spring Boot REST APIs, JPA setups, and database connections on our YouTube channel.

▶ Subscribe to Spring Java Lab

📘 What to Learn After Spring Boot JPA Basics?

Mastering Spring Boot JPA basics is just the first step. To become job-ready and production-capable, explore these related tutorials to deepen your enterprise architecture skills.

🧩 Spring Boot CRUD API (Oracle DB)

Build complete CRUD REST APIs using Spring Boot, JPA, and a real database.

📄 Pagination & Sorting

Learn how to efficiently handle massive database tables using Pageable and PageRequests.

🔍 Dynamic Filtering (JPA Specs)

Implement dynamic, complex search queries using JPA Specifications for real-world APIs.

🗄️ Database Performance Tuning

Move beyond the basics and learn how JPA configurations impact performance in live systems.

🚨 Global Exception Handling

Handle database constraint violations and validation errors cleanly using @RestControllerAdvice.

🎓 Spring Boot Interview Qs (Freshers)

Prepare for entry-level interviews covering core JPA, repositories, and dependency injection concepts.