π¦ Data Persistence Basics: Your Database Filing Cabinet
Imagine you have a magical filing cabinet that never forgets anything. Thatβs what Jakarta Persistence does for your Java apps!
π― The Big Picture
Think of your computer like a forgetful friend. Every time you turn it off, it forgets everything! But we need our apps to remember things - like your high score, your profile, or your shopping cart.
Jakarta Persistence (JPA) is like giving your Java app a super-organized filing cabinet that:
- π Saves your data safely
- π Finds it quickly when needed
- π Keeps everything organized
πΊοΈ What Weβll Learn
graph TD A["Jakarta Persistence Overview"] --> B["Persistence XML"] B --> C["Persistence Unit"] C --> D["Entity Classes"] D --> E["Entity Lifecycle"] E --> F["Entity States"] style A fill:#667eea,color:#fff style B fill:#764ba2,color:#fff style C fill:#f093fb,color:#fff style D fill:#f5576c,color:#fff style E fill:#4facfe,color:#fff style F fill:#00f2fe,color:#fff
1οΈβ£ Jakarta Persistence Overview
What Is It?
Jakarta Persistence (formerly called JPA) is like a translator between your Java code and your database.
| You Say (Java) | Database Hears (SQL) |
|---|---|
save(student) |
INSERT INTO students... |
find(5) |
SELECT * WHERE id=5 |
delete(student) |
DELETE FROM students... |
Why Do We Need It?
Without JPA π«
// So much work!
String sql = "INSERT INTO students " +
"(name, age) VALUES (?, ?)";
PreparedStatement ps =
conn.prepareStatement(sql);
ps.setString(1, "Emma");
ps.setInt(2, 10);
ps.executeUpdate();
With JPA π
// So simple!
Student emma = new Student();
emma.setName("Emma");
emma.setAge(10);
entityManager.persist(emma);
The Magic Explained
JPA works like a librarian:
- π You give them a book (your data object)
- π They know exactly where to put it (the database)
- π They can find it instantly when you ask
2οΈβ£ Persistence XML Configuration
What Is persistence.xml?
Think of persistence.xml as the recipe card for your filing cabinet. It tells JPA:
- π Where is the database?
- π Whatβs the password?
- βοΈ How should things work?
Where Does It Live?
π your-project/
π src/main/resources/
π META-INF/
π persistence.xml β Here!
Basic Structure
<?xml version="1.0"?>
<persistence
xmlns="https://jakarta.ee/xml/ns/persistence"
version="3.0">
<persistence-unit name="myApp">
<!-- Settings go here -->
</persistence-unit>
</persistence>
Essential Settings Explained
| Setting | What It Does | Example |
|---|---|---|
name |
Names your config | "schoolDB" |
provider |
Which JPA engine | Hibernate, EclipseLink |
class |
Your data classes | Student, Teacher |
Complete Example
<?xml version="1.0"?>
<persistence
xmlns="https://jakarta.ee/xml/ns/persistence"
version="3.0">
<persistence-unit name="schoolDB">
<!-- The engine that does the work -->
<provider>
org.hibernate.jpa.HibernatePersistenceProvider
</provider>
<!-- Our data classes -->
<class>com.school.Student</class>
<class>com.school.Teacher</class>
<!-- Database connection -->
<properties>
<property name="jakarta.persistence.jdbc.url"
value="jdbc:h2:./mydb"/>
<property name="jakarta.persistence.jdbc.user"
value="admin"/>
<property name="jakarta.persistence.jdbc.password"
value="secret123"/>
</properties>
</persistence-unit>
</persistence>
3οΈβ£ Persistence Unit
What Is a Persistence Unit?
A Persistence Unit is like a team that works together:
- π’ One database
- π¦ A group of related entities
- βοΈ Shared settings
Real-World Analogy
Think of a school with different offices:
| Persistence Unit | Contains | Database |
|---|---|---|
studentUnit |
Students, Grades | student_db |
libraryUnit |
Books, Loans | library_db |
cafeteriaUnit |
Meals, Orders | food_db |
Why Multiple Units?
Sometimes you need separate filing cabinets:
- π Different security levels
- π Different databases
- π Different configurations
Creating an EntityManager
// Step 1: Create the factory
EntityManagerFactory factory =
Persistence.createEntityManagerFactory(
"schoolDB" // matches persistence.xml
);
// Step 2: Get a manager to do the work
EntityManager em =
factory.createEntityManager();
// Step 3: Use it!
Student found = em.find(Student.class, 1);
4οΈβ£ Entity Classes
What Is an Entity?
An Entity is a Java class that represents one row in a database table.
graph LR A["Java Object"] -->|"@Entity"| B["Database Row"] style A fill:#667eea,color:#fff style B fill:#4facfe,color:#fff
The Magic Annotation
Just add @Entity to any class:
@Entity // β This is the magic word!
public class Student {
@Id // β Every entity needs an ID
private Long id;
private String name;
private int age;
// Getters and setters...
}
Essential Annotations
| Annotation | Purpose | Required? |
|---|---|---|
@Entity |
βThis is a database thingβ | β Yes |
@Id |
βThis is the unique IDβ | β Yes |
@Table |
Custom table name | Optional |
@Column |
Custom column name | Optional |
Complete Entity Example
@Entity
@Table(name = "students") // Table name
public class Student {
@Id
@GeneratedValue(strategy = AUTO)
private Long id; // Auto-generated!
@Column(name = "full_name")
private String name;
@Column(nullable = false)
private int age; // Can't be empty
private String email; // Uses "email" as column
// Constructor
public Student() {}
// Getters and setters...
}
What Gets Created?
students table:
ββββββ¬ββββββββββββ¬ββββββ¬ββββββββββββββββββ
β id β full_name β age β email β
ββββββΌββββββββββββΌββββββΌββββββββββββββββββ€
β 1 β Emma β 10 β emma@school.com β
β 2 β Liam β 11 β liam@school.com β
ββββββ΄ββββββββββββ΄ββββββ΄ββββββββββββββββββ
5οΈβ£ Entity Lifecycle
The Journey of an Entity
Every entity goes through a lifecycle - like a butterfly! π¦
graph TD A["π₯ New Object"] -->|persist| B["π¦ Managed"] B -->|detach| C["π Detached"] B -->|remove| D["ποΈ Removed"] C -->|merge| B style A fill:#ffeaa7,color:#000 style B fill:#55efc4,color:#000 style C fill:#74b9ff,color:#000 style D fill:#fd79a8,color:#000
Lifecycle Operations
| Operation | What Happens | When To Use |
|---|---|---|
persist() |
Saves new entity | Adding new data |
merge() |
Updates existing | Editing data |
remove() |
Deletes entity | Removing data |
find() |
Gets by ID | Looking up data |
detach() |
Disconnects | Sending outside |
Code Examples
Creating (persist)
Student emma = new Student();
emma.setName("Emma");
em.persist(emma); // Now saved!
Reading (find)
Student found = em.find(Student.class, 1L);
System.out.println(found.getName());
Updating (merge)
emma.setAge(11); // Change something
em.merge(emma); // Save changes
Deleting (remove)
em.remove(emma); // Gone forever!
6οΈβ£ Entity States
The Four States
Every entity is in one of four states at any moment:
| State | Icon | Meaning |
|---|---|---|
| New | π | Just created, not saved yet |
| Managed | β | Being tracked by JPA |
| Detached | π | Was tracked, now disconnected |
| Removed | ποΈ | Marked for deletion |
State Transitions Explained
graph TD subgraph "Not in Database" N["π NEW"] end subgraph "In Database" M["β MANAGED"] D["π DETACHED"] R["ποΈ REMOVED"] end N -->|"persist#40;#41;"| M M -->|"detach#40;#41; or close#40;#41;"| D M -->|"remove#40;#41;"| R D -->|"merge#40;#41;"| M R -->|"persist#40;#41;"| M style N fill:#ffeaa7,color:#000 style M fill:#55efc4,color:#000 style D fill:#74b9ff,color:#000 style R fill:#fd79a8,color:#000
π NEW State
// Just created - not in database yet
Student emma = new Student();
emma.setName("Emma");
// emma is NEW - no ID, not tracked
β MANAGED State
em.persist(emma);
// Now emma is MANAGED!
// - Has an ID
// - Changes are tracked automatically
emma.setAge(10); // This will be saved!
π DETACHED State
em.detach(emma);
// Now emma is DETACHED
// - Still has data
// - Changes are NOT tracked
emma.setAge(11); // This WON'T be saved!
ποΈ REMOVED State
em.remove(emma);
// Now emma is REMOVED
// - Will be deleted on commit
// - Still exists in memory temporarily
Why States Matter
Understanding states prevents common bugs:
| Problem | Cause | Solution |
|---|---|---|
| βChanges not saving!β | Entity is DETACHED | Use merge() |
| βDuplicate entry!β | Entity already MANAGED | Check before persist() |
| βEntity not found!β | Entity was REMOVED | Donβt use after remove() |
π You Made It!
You now understand the foundation of Jakarta Persistence:
| Concept | Your Understanding |
|---|---|
| β JPA Overview | Translator between Java and Database |
| β persistence.xml | The recipe/settings file |
| β Persistence Unit | A team of entities + database |
| β Entity Classes | Java objects that become table rows |
| β Entity Lifecycle | persist β merge β remove |
| β Entity States | New β Managed β Detached β Removed |
π Quick Reference
// 1. Create entity
Student s = new Student(); // NEW
// 2. Save it
em.persist(s); // MANAGED
// 3. Find it
Student found = em.find(
Student.class, 1L); // MANAGED
// 4. Update it
found.setName("New Name"); // Auto-saved!
// 5. Delete it
em.remove(found); // REMOVED
π‘ Remember: JPA is your friendly librarian. Give it your Java objects, and it handles all the database work for you!
