0
0
Spring Bootframework~5 mins

JPA entity with @Entity annotation in Spring Boot

Choose your learning style9 modes available
Introduction

The @Entity annotation marks a class as a database table. It helps Spring Boot know which classes to save and load from the database.

When you want to store user information like name and email in a database.
When you need to save product details for an online store.
When you want to keep track of orders or transactions in your app.
When you want to map Java objects to database tables automatically.
Syntax
Spring Boot
@Entity
public class ClassName {
    @Id
    private Long id;
    // other fields
}

The class must have a unique identifier marked with @Id.

The class name usually matches the table name but can be customized.

Examples
This example shows a simple User entity with id, name, and email fields.
Spring Boot
@Entity
public class User {
    @Id
    private Long id;
    private String name;
    private String email;
}
This example defines a Product entity with a productId as the unique key.
Spring Boot
@Entity
public class Product {
    @Id
    private Long productId;
    private String productName;
    private double price;
}
Sample Program

This is a complete JPA entity class named Book. It has an @Entity annotation to mark it as a database table. The id field is the unique identifier marked with @Id. It includes constructors, getters, setters, and a toString method for easy printing.

Spring Boot
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class Book {
    @Id
    private Long id;
    private String title;
    private String author;

    public Book() {}

    public Book(Long id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book{id=" + id + ", title='" + title + "', author='" + author + "'}";
    }
}
OutputSuccess
Important Notes

Every entity needs a field annotated with @Id to serve as the primary key.

Use a no-argument constructor so frameworks can create instances easily.

Fields without annotations are mapped to columns with the same name by default.

Summary

@Entity marks a class as a database table.

Each entity needs a unique @Id field.

Entities help connect Java objects with database records automatically.