0Pricing
Spring Boot 4 Microservices & REST APIs · Pelajaran

Mengintegrasikan Basis Data H2 dan JPA

Siapkan basis data H2 dalam memori dan konfigurasikan Spring Data JPA untuk persistensi data.

Mengintegrasikan Basis Data H2 dan JPA adalah pelajaran Spring Boot 4 Microservices & REST APIs gratis di CoddyKit. Ini adalah pelajaran 1 dari 6. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Spring Boot 4 Microservices & REST APIs, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Spring Boot 4 Microservices & REST APIs mencakup 6 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

Storing Data with Persistence

Welcome! In this lesson, we'll learn about data persistence. This is how applications save information so it's not lost when the app closes.

Think of it like saving a document on your computer. Without persistence, all your work would vanish every time you shut down.

Introducing JPA

JPA stands for Java Persistence API. It's a standard for managing relational data in Java applications.

JPA helps map Java objects to database tables, a process called Object-Relational Mapping (ORM). This lets you work with objects instead of writing complex SQL queries.

Simplifying with Spring Data JPA

While JPA is a standard, Spring Data JPA makes using it even easier! It's part of the Spring framework.

Spring Data JPA provides powerful abstractions, letting you create data repositories with minimal code. You often just declare an interface, and Spring handles the implementation!

H2: An In-Memory Database

For development, we'll use H2 Database. It's a lightweight, open-source relational database.

  • In-Memory: It runs entirely in your application's memory, making it super fast for development.
  • Easy Setup: No separate installation needed; just add a dependency.
  • Console: It comes with a web console to view your data.

It's perfect for testing and quickly building prototypes.

Project Dependencies for H2 & JPA

To use H2 and Spring Data JPA in a Spring Boot project, we need to add specific dependencies to our pom.xml file.

These dependencies tell Maven (our build tool) which libraries to include.

<pre><code>&lt;dependencies&gt;
    &lt;!-- Spring Data JPA --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
    &lt;/dependency&gt;

    &lt;!-- H2 Database --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;com.h2database&lt;/groupId&gt;
        &lt;artifactId&gt;h2&lt;/artifactId&gt;
        &lt;scope&gt;runtime&lt;/scope&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;</code></pre>

Spring Boot's Smart Setup

One of Spring Boot's superpowers is auto-configuration. When it sees the H2 and Spring Data JPA dependencies, it automatically sets up a database connection and configures JPA for you.

This means less boilerplate code and faster development! It typically defaults to an in-memory H2 database.

Customizing H2 in `application.properties`

While Spring Boot auto-configures H2, we often want to enable its web console for easy viewing of our database. We do this in src/main/resources/application.properties.

Add these lines to your application.properties file:

<pre><code>spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=</code></pre>

Accessing Your H2 Console

Once your Spring Boot application starts with the above configuration, you can access the H2 console through your web browser.

  • Open your browser.
  • Go to http://localhost:8080/h2-console (if your app runs on port 8080).
  • Use the JDBC URL jdbc:h2:mem:testdb and the username sa (no password) to connect.

You'll see a simple interface to browse tables and run SQL queries.

Defining a Simple Data Model

Now, let's create a simple Java class that JPA will map to a database table. This is called an Entity.

We use @Entity to mark it as a JPA entity and @Id to denote its primary key.

<pre><code>package com.coddykit.lesson;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

    // Getters and setters (omitted for brevity)
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
}</code></pre>

Data Access with `JpaRepository`

To interact with our Product entity, we define a repository interface. Spring Data JPA will automatically provide the implementation.

By extending JpaRepository<Product, Long>, we get basic CRUD (Create, Read, Update, Delete) operations for free!

<pre><code>package com.coddykit.lesson;

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

@Repository
public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {
    // Spring Data JPA automatically provides methods
    // like save(), findById(), findAll(), deleteById()
}</code></pre>

Quick Check: H2 & JPA Setup

Which of the following dependencies are essential for setting up an in-memory H2 database with Spring Data JPA in a Spring Boot project?

H2 & JPA: Ready to Persist!

Great job! In this lesson, you learned how to:

  • Understand data persistence and JPA.
  • Integrate H2 Database and Spring Data JPA into your project.
  • Configure H2 and access its web console.
  • Define a basic JPA Entity and a JpaRepository interface.

You've laid the groundwork for building data-driven Spring Boot applications!

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Mengintegrasikan Basis Data H2 dan JPA” gratis?

Ya — teks lengkap “Mengintegrasikan Basis Data H2 dan JPA” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Spring Boot 4 Microservices & REST APIs, upgrade ke CoddyKit PRO. Kursus Spring Boot 4 Microservices & REST APIs mencakup 6 pelajaran total.

Apa yang akan aku pelajari di “Mengintegrasikan Basis Data H2 dan JPA”?

Siapkan basis data H2 dalam memori dan konfigurasikan Spring Data JPA untuk persistensi data. Kamu berlatih Spring Boot 4 Microservices & REST APIs dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai Spring Boot 4 Microservices & REST APIs?

Tidak diperlukan pengalaman sebelumnya. Spring Boot 4 Microservices & REST APIs di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 1 dari 6.

Berapa lama pelajaran “Mengintegrasikan Basis Data H2 dan JPA” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran Spring Boot 4 Microservices & REST APIs ini?

Ya. Setiap pelajaran Spring Boot 4 Microservices & REST APIs menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Mengintegrasikan Basis Data H2 dan JPA
  2. Pengantar Spring Data JPA
  3. Membuat Entitas dan Repositori
  4. Mendefinisikan Entitas dan Repositori
  5. Operasi CRUD dengan REST
  6. Melakukan Operasi CRUD
← Kembali ke Spring Boot 4 Microservices & REST APIs