Créer des entités et des référentiels
Définissez des entités JPA pour représenter votre modèle de données et utilisez les référentiels Spring Data pour accéder aux données.
Créer des entités et des référentiels est une leçon Spring Boot 4 Microservices & REST APIs gratuite sur CoddyKit. Ceci est la leçon 3 sur 6. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Spring Boot 4 Microservices & REST APIs, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Spring Boot 4 Microservices & REST APIs comprend 6 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
What are JPA Entities?
Welcome to creating your data model! In Spring Boot with JPA, an Entity is a plain Java object that represents a table in your database.
Think of it as a blueprint for the rows in your table. Each instance of an entity class corresponds to a single row in the database table.
Marking a Class as an Entity
To tell Spring Boot that a Java class is an entity, we use the @Entity annotation. This annotation comes from the Java Persistence API (JPA).
When Spring sees @Entity, it knows to map this class to a database table. By default, the table name will be the same as the class name (e.g., a Product class maps to a Product table).
Defining Primary Keys with @Id
Every database table needs a primary key to uniquely identify each record. In JPA, we mark a field as the primary key using the @Id annotation.
Often, we want the database to automatically generate this ID for us. For this, we use the @GeneratedValue annotation, typically with a strategy like IDENTITY for auto-incrementing numbers.
Our First Product Entity
Let's create a simple Product entity. It will have an ID, a name, and a price. Notice the annotations @Entity, @Id, and @GeneratedValue.
Remember to include a default constructor and getters/setters for JPA to work correctly.
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;
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 +
'}';
}
}Introducing Spring Data Repositories
Now that we have an entity, how do we interact with the database to save, retrieve, update, or delete products? This is where Repositories come in!
Spring Data JPA provides a powerful abstraction that simplifies data access. Instead of writing complex SQL queries, you define simple interfaces.
The JpaRepository Interface
The core of Spring Data JPA is the JpaRepository interface. When your repository interface extends JpaRepository, Spring automatically provides standard CRUD (Create, Read, Update, Delete) methods for your entity.
You just need to specify the entity type and the type of its primary key, like this: JpaRepository<YourEntity, ID_Type>.
Defining Our Product Repository
Let's create a repository for our Product entity. It's just an interface that extends JpaRepository, telling Spring to generate the necessary code for us.
We specify Product as the entity type and Long as the primary key type.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
// Spring Data JPA automatically provides methods like:
// save(), findById(), findAll(), deleteById(), etc.
}Using Repositories in Spring
In a Spring Boot application, you would typically inject your repository into a service or controller using @Autowired. Then, you can call the built-in methods.
repository.save(product): Saves a new product or updates an existing one.repository.findById(id): Finds a product by its ID.repository.findAll(): Retrieves all products.
Entity & Repository in Action
Here's a conceptual example showing how an entity is created and how a repository would save it. We're simulating the repository behavior to make it runnable without a full Spring Boot setup.
This demonstrates creating a Product object and using a 'save' method.
// --- Simulated Product Entity --- //
class Product {
private Long id;
private String name;
private double price;
public Product(Long id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
// Getters and Setters (simplified 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; }
@Override
public String toString() {
return "Product{id=" + id + ", name='" + name + "', price=" + price + "}";
}
}
// --- Simulated Product Repository Interface --- //
interface ProductRepository {
Product save(Product product);
}
// --- Simulated Product Repository Implementation --- //
class SimpleProductRepository implements ProductRepository {
private static Long nextId = 1L;
@Override
public Product save(Product product) {
if (product.getId() == null) {
product.setId(nextId++); // Assign a new ID
}
System.out.println("Simulating save: " + product);
return product;
}
}
public class Main {
public static void main(String[] args) {
// 1. Create a Product entity instance
Product newProduct = new Product(null, "Wireless Earbuds", 99.99);
System.out.println("Created product: " + newProduct);
// 2. Simulate saving it using our repository
ProductRepository repository = new SimpleProductRepository();
Product savedProduct = repository.save(newProduct);
System.out.println("Product after simulated save: " + savedProduct);
}
}Quick Check: Core Concepts
Which of the following annotations is used to mark a class as a JPA entity that maps to a database table?
Recap: Entities & Repositories
You've learned the fundamentals of defining your data model with Spring Data JPA!
- Entities are Java objects representing database tables, marked with
@Entity. - Primary keys are defined with
@Idand often auto-generated using@GeneratedValue. - Repositories are interfaces that extend
JpaRepository, providing powerful, ready-to-use methods for interacting with your database.
These two concepts are the cornerstone of data persistence in Spring Boot.
Apprends Java avec un tuteur IA — gratuit
Écris et exécute du vrai code dans ton navigateur, obtiens de l'aide instantanée d'un tuteur IA disponible 24h/24, et reprends là où tu t'es arrêté sur le web ou dans l'app.
- Cours
- 24
- Leçons
- 93
Questions Fréquemment Posées
La leçon « Créer des entités et des référentiels » est-elle gratuite ?
Oui — le texte complet de « Créer des entités et des référentiels » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Spring Boot 4 Microservices & REST APIs, passe à CoddyKit PRO. Le cours Spring Boot 4 Microservices & REST APIs comprend 6 leçons au total.
Qu'est-ce que j'apprendrai dans « Créer des entités et des référentiels » ?
Définissez des entités JPA pour représenter votre modèle de données et utilisez les référentiels Spring Data pour accéder aux données. Tu pratiques Spring Boot 4 Microservices & REST APIs avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Spring Boot 4 Microservices & REST APIs ?
Aucune expérience préalable n'est requise. Spring Boot 4 Microservices & REST APIs sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 6.
Combien de temps prend la leçon « Créer des entités et des référentiels » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Spring Boot 4 Microservices & REST APIs ?
Oui. Chaque leçon Spring Boot 4 Microservices & REST APIs inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Intégrer une base de données H2 et JPA
- Introduction à Spring Data JPA
- Créer des entités et des référentiels
- Définir les entités et les référentiels
- Opérations CRUD avec REST
- Effectuer des opérations CRUD