π Study Material β JPA and Hibernate
Welcome to Week 6. In this module, you will learn how backend applications interact with databases using JPA and Hibernate.
π§ 1. What is ORM (Object Relational Mapping)?
In Java, we work with objects.
In databases, data is stored in tables.
ORM helps us map:
| Java | Database |
|---|---|
| Class | Table |
| Object | Row |
| Field | Column |
Without ORM:
- You write SQL manually
- You map data manually
With ORM:
- Java objects are automatically mapped to database tables
- You focus on business logic instead of SQL
π§© 2. What is JPA?
JPA (Java Persistence API) is a specification.
It defines:
- How Java objects should be mapped to database tables
- Standard annotations
- APIs for persistence
π JPA itself does NOT implement anything.
βοΈ 3. What is Hibernate?
Hibernate is the most popular implementation of JPA.
It provides:
- Actual ORM functionality
- Query execution
- Caching
- Transaction handling
π In simple terms:
- JPA = Rules
- Hibernate = Implementation
π 4. Basic JPA Setup in Spring Boot
Spring Boot simplifies everything.
Add dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Database configuration (application.properties):
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
π§± 5. Creating an Entity
An entity represents a table in the database.
Example:
import jakarta.persistence.*;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters
}
π Important Annotations
@Entityβ Marks class as database entity@Tableβ Specifies table name@Idβ Primary key@GeneratedValueβ Auto-generates ID
π¦ 6. Repository Layer
Spring Data JPA provides ready-to-use repository interfaces.
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, Long> {
}
π₯ What You Get Automatically
Without writing any code, you get:
- save()
- findById()
- findAll()
- deleteById()
π 7. CRUD Operations
Example Service:
@Service
public class StudentService {
@Autowired
private StudentRepository repository;
public Student save(Student student) {
return repository.save(student);
}
public List<Student> getAll() {
return repository.findAll();
}
public void delete(Long id) {
repository.deleteById(id);
}
}
π 8. Entity Relationships
Real-world data is connected.
πΉ One-to-Many
Example:
- One Student β Many Courses
@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
private List<Course> courses;
πΉ Many-to-One
@ManyToOne
@JoinColumn(name = "student_id")
private Student student;
πΉ One-to-One
@OneToOne
@JoinColumn(name = "profile_id")
private Profile profile;
β‘ 9. Fetch Types
Defines when data is loaded.
πΉ EAGER
- Loads data immediately
- Can impact performance
πΉ LAZY
- Loads data only when needed
- Recommended in most cases
@OneToMany(fetch = FetchType.LAZY)
β οΈ 10. Common Pitfalls
β LazyInitializationException
Occurs when:
- Session is closed
- Lazy data accessed outside transaction
β N+1 Query Problem
Too many queries executed unnecessarily.
β Missing Transactions
Always ensure service methods are transactional when needed.
π 11. Query Methods
Spring Data JPA allows custom queries using method names.
List<Student> findByName(String name);
List<Student> findByEmailContaining(String keyword);
π§ͺ 12. Testing APIs
Use Postman:
- POST β Create student
- GET β Fetch students
- DELETE β Remove student
π§± 13. Layered Architecture
Follow this structure:
Controller β Service β Repository β Database
Never:
- Access repository directly from controller
- Mix business logic in controller
π‘ 14. Best Practices
- Use DTOs (Do not expose entities directly)
- Keep entities simple
- Avoid bidirectional relationships unless needed
- Use LAZY fetching
- Write clean repository methods
- Handle exceptions properly
π§ Summary
In this module, you learned:
- What ORM is
- Difference between JPA and Hibernate
- How to create entities
- How to use repositories
- How to implement relationships
- How backend applications persist data
π Whatβs Next?
Proceed to:
π Exercises
Practice is critical for mastering JPA and Hibernate.
π₯ Why this is effective
- Progressive learning (concept β code β pitfalls β best practices)
- Avoids overwhelming theory
- Includes real-world warnings (very important for beginners)
- Prepares her for assignment + review