DEV Community

Cover image for Create an Entity and Repository using Spring Boot 3
William
William

Posted on

Create an Entity and Repository using Spring Boot 3

In the last post I started creating the project's file and some configuration, to let things more interested, let's create our first classes, in specific the entity and repository classes.

Create the Entity class

How the focus is the REST API, the Entity will be simple,
Create a classe Product inside the new folder models.

package com.spring.models;

import jakarta.persistence.*;

import java.io.Serializable;
import java.util.UUID;

@Entity
@Table(name = "products")
public class Product implements Serializable {

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

    @Column(length = 125, nullable = false)
    private String name;

    @Column(nullable = false)
    private Double price;

    @Column
    private String description;

    public Product() {
    }
    //get and sets
}

Enter fullscreen mode Exit fullscreen mode

The @Entity annotation means that this classes is a Entity and using with @Table annotation specifies that the table is Products.
The table Products has a primary key id and 3 column name, price and description, each column is represent by a var with annotation @Column.
This class also have the gets and sets!

Create the Repository interface

To be able to access the table information, it's necessary to create a repository class.
Using Spring Boot implementing this is simple.
Create a interface with the name ProductRepository inside the new folder repositories.

package com.spring.repositories;

import com.spring.models.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
Enter fullscreen mode Exit fullscreen mode

The @Repository annotation means to the Spring Boot that this interface is a Repository.
The JpaRepository interface is used to say that this repository is about Product entity and it's primary key is Long type.

Run the project

When you run the project, the Products table will be create in the database, because in the application.properties has this
spring.jpa.hibernate.ddl-auto=update.

produts table

Conclusion

In this post, we create the Entity and Repository classes about Product, also we saw important annotations and their used to create this classes.

Next Step

In the next step we will create the service and controller classes, and make some test using Postman.

Top comments (0)