0Pricing
Spring Boot 4 Microservices & REST APIs · 강의

H2 데이터베이스 및 JPA 통합

인메모리 H2 데이터베이스를 설정하고 데이터 영속성을 위해 Spring Data JPA를 구성합니다.

H2 데이터베이스 및 JPA 통합은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 6개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Microservices & REST APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 6개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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!

자주 묻는 질문

“H2 데이터베이스 및 JPA 통합” 강의는 무료인가요?

네 — “H2 데이터베이스 및 JPA 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 6개의 강의가 포함되어 있습니다.

“H2 데이터베이스 및 JPA 통합”에서 뭘 배우나요?

인메모리 H2 데이터베이스를 설정하고 데이터 영속성을 위해 Spring Data JPA를 구성합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Microservices & REST APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 1번째 강의입니다.

“H2 데이터베이스 및 JPA 통합” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Boot 4 Microservices & REST APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. H2 데이터베이스 및 JPA 통합
  2. Spring Data JPA 입문
  3. 엔터티 및 리포지터리 만들기
  4. 엔터티 및 리포지토리 정의
  5. REST로 CRUD 작업 구현하기
  6. CRUD 작업 수행
← Spring Boot 4 Microservices & REST APIs(으)로 돌아가기