0Pricing
Spring Boot 4 Microservices & REST APIs · 课时

定义实体与存储库

创建映射到数据库表的 JPA 实体,并定义用于数据访问的存储库接口。

定义实体与存储库 是 CoddyKit 上的免费 Spring Boot 4 Microservices & REST APIs 课时。 这是第 4 节课,共 6 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Microservices & REST APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Microservices & REST APIs 课程共包含 6 节课。

本课时的部分内容尚未翻译,以英文显示。

Welcome to Data Persistence

In this lesson, we'll learn how to connect your Java application to a database using Spring Boot. This is called data persistence, meaning your data lives on even after your app stops.

We'll focus on two core concepts:

  • Entities: Your Java objects that map to database tables.
  • Repositories: Interfaces that provide easy ways to interact with your entities and the database.

What's a JPA Entity?

A JPA Entity is a plain Java class that represents a table in your relational database. Each instance of this class corresponds to a row in that table.

The Java Persistence API (JPA) is a standard for managing relational data in Java applications. Spring Data JPA builds on this to simplify database interactions even further.

Defining Your First Entity

To mark a Java class as a JPA Entity, you use the @Entity annotation. You also need to define a primary key using @Id.

Let's create a simple Product entity:

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class Product {

    @Id
    private Long id;
    private String name;
    private double price;

    public Product() {}

    public Product(Long id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    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;
    }

    @Override
    public String toString() {
        return "Product{id=" + id + ", name='" + name + "', price=" + price + "}";
    }

    public static void main(String[] args) {
        Product product = new Product(1L, "Laptop", 1200.00);
        System.out.println(product);
    }
}

Auto-Generating Primary Keys

Manually assigning IDs can be tedious and prone to errors. Databases can automatically generate unique IDs for you!

Use the @GeneratedValue annotation along with a strategy. GenerationType.IDENTITY is common for databases that auto-increment (like MySQL, H2).

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

@Entity
public class Product {

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

    public Product() {}

    public Product(String name, double price) { // No ID in constructor
        this.name = name;
        this.price = price;
    }

    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;
    }

    @Override
    public String toString() {
        return "Product{id=" + id + ", name='" + name + "', price=" + price + "}";
    }

    public static void main(String[] args) {
        Product product = new Product("Keyboard", 75.00);
        // In a real app, ID would be generated by the DB when persisted
        System.out.println("Product created (ID will be generated by DB): " + product);
    }
}

Customizing Column Mappings

By default, JPA maps fields to columns with the same name. You can customize this using the @Column annotation.

It lets you specify the column name, whether it's nullable, its length, and more:

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

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "product_name", nullable = false, length = 100)
    private String name;

    @Column(nullable = false)
    private double price;

    public Product() {}

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    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;
    }

    @Override
    public String toString() {
        return "Product{id=" + id + ", name='" + name + "', price=" + price + "}";
    }

    public static void main(String[] args) {
        Product product = new Product("Mouse", 25.50);
        System.out.println("Product with custom columns: " + product);
    }
}

Introducing Spring Data Repositories

Now that we have an entity, how do we save it to the database or retrieve it? That's where Spring Data Repositories come in!

A repository is an interface that provides powerful, pre-built methods for common database operations (like Create, Read, Update, Delete - CRUD). You don't write SQL; Spring Data JPA generates it for you.

Defining a JpaRepository Interface

To create a repository for your entity, you simply define an interface that extends Spring Data JPA's JpaRepository.

The JpaRepository takes two type parameters: the Entity type and the type of its Primary Key.

Here's how you'd define a repository for our Product entity:

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

// Assuming 'Product' entity is defined in the same package or imported
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    // Spring Data JPA automatically provides CRUD methods here!
    // You can add custom query methods if needed, e.g.,
    // List<Product> findByName(String name);
}

Note: The @Repository annotation is optional but good practice for clarity.

Built-in Repository Methods

By extending JpaRepository, your ProductRepository automatically inherits many powerful methods. Here are a few:

  • save(entity): Saves a given entity (inserts if new, updates if exists).
  • findById(id): Retrieves an entity by its ID, returning an Optional.
  • findAll(): Returns all instances of the entity type.
  • delete(entity) or deleteById(id): Removes an entity.

This means you get full CRUD functionality without writing a single line of implementation code!

Using Repositories in an App

In a real Spring Boot application, you would inject your repository into a service or controller using @Autowired and then call its methods.

While we can't run a full Spring Boot app with a database here, this snippet shows the conceptual usage within a typical Spring Boot component:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

// Assuming Product and ProductRepository are defined

@Service
public class ProductService {

    private final ProductRepository productRepository;

    @Autowired
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public Product createProduct(String name, double price) {
        Product newProduct = new Product(name, price);
        return productRepository.save(newProduct);
    }

    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    public Product getProductById(Long id) {
        return productRepository.findById(id).orElse(null);
    }
}

This ProductService would then be used by other parts of your application.

Quick Check on Entities

Which of the following annotations are essential for defining a basic JPA Entity that maps to a database table and has an auto-generated primary key?

Recap: Entities & Repositories

Great job! You've learned the foundations of data persistence with Spring Data JPA:

  • Entities are Java classes annotated with @Entity that map to database tables.
  • @Id marks the primary key, and @GeneratedValue lets the database handle ID generation.
  • @Column allows you to customize field-to-column mappings.
  • Repositories are interfaces that extend JpaRepository<Entity, ID>, providing powerful, ready-to-use CRUD methods without writing SQL.

Next, you'll dive deeper into performing various CRUD operations!

常见问题解答

「定义实体与存储库」课时是免费的吗?

是的 — 「定义实体与存储库」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Microservices & REST APIs 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Microservices & REST APIs 课程共包含 6 节课。

「定义实体与存储库」这节课中我会学到什么?

创建映射到数据库表的 JPA 实体,并定义用于数据访问的存储库接口。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Microservices & REST APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Boot 4 Microservices & REST APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Boot 4 Microservices & REST APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 6 节。

「定义实体与存储库」课时需要多长时间?

大多数 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. 执行增删改查操作
← 返回 Spring Boot 4 Microservices & REST APIs