Entities
Entities are the heart of JPA. An entity is just a regular Java class that maps to a database table. Each object of an entity class represents a row in that table. Simple as that.
You mark a class as an entity using the @Entity annotation. This tells Spring "hey, this class is special, it lives in the database." Without this annotation, JPA won't know about your class.
@Id and @GeneratedValue
Every entity needs a primary key. That's what @Id is for. It tells JPA which field uniquely identifies each row. Without an ID, your entity is like a phone without a number, it can't be found.
The @GeneratedValue annotation makes the database auto-generate IDs for you. You don't need to worry about what the next ID will be. The database handles it. Usually you use GenerationType.IDENTITY or GenerationType.IDENTITY for auto-increment.
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
}
@Column Annotation
By default, JPA maps field names directly to column names. But sometimes you want more control. The @Column annotation lets you customize the column name, set it as nullable, or define a maximum length.
For example, if your field is called "userEmail" but your database column is "email_address", you use @Column(name = "email_address"). It also helps keep your database schema clean and predictable.
@Column(name = "email_address", nullable = false, length = 100)
private String email;
Entity Relationships
Real-world data has relationships. A user has many orders. An order belongs to one user. JPA handles this with annotations like @OneToMany, @ManyToOne, @ManyToMany, and @OneToOne.
@OneToMany means one entity is related to many of another. Think of a department having many employees. @ManyToOne is the flip side, each employee belongs to one department. These annotations tell JPA how to join tables together.
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
private BigDecimal totalAmount;
}
Try it Yourself โ