Entity and Configuration

Back

Loading concept...

πŸ“¦ 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:

  1. πŸ“ You give them a book (your data object)
  2. πŸ“š They know exactly where to put it (the database)
  3. πŸ” 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!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.