JPA map class Java ↔ bảng DB qua annotation — không viết SQL DDL thủ công.
@Entity
@Table(name = "users")
class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
@Column(unique = true)
private String email;
}Annotation cơ bản:
- @Entity — đánh dấu class là JPA entity (1 bảng).
- @Table(name=...) — tên bảng (mặc định = tên class).
- @Id — khóa chính.
- @GeneratedValue — cách sinh ID: IDENTITY (auto-increment, phổ biến nhất với MySQL/Postgres), SEQUENCE, UUID.
- @Column — ràng buộc cột (nullable, length, unique).
Quan hệ entity:
@Entity
class Order {
@Id @GeneratedValue Long id;
@ManyToOne(fetch = FetchType.LAZY) // nhiều order thuộc 1 user
@JoinColumn(name = "user_id")
private User user;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private List<OrderItem> items;
}@ManyToOne/@OneToMany— quan hệ 1-nhiều (bên "nhiều" giữ FK).@JoinColumn— tên cột foreign key.mappedBy— bên không sở hữu quan hệ (tránh tạo bảng join thừa).fetch = LAZY— khuyến nghị mặc định để tránh N+1 (xem câu N+1).
Lưu ý: dùng GenerationType.IDENTITY thì Hibernate không batch insert được. Production tải cao thường dùng SEQUENCE.
JPA maps Java classes ↔ DB tables via annotations — no manual SQL DDL.
@Entity
@Table(name = "users")
class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
@Column(unique = true)
private String email;
}Basic annotations:
- @Entity — marks the class as a JPA entity (one table).
- @Table(name=...) — table name (defaults to the class name).
- @Id — primary key.
- @GeneratedValue — ID generation: IDENTITY (auto-increment, most common with MySQL/Postgres), SEQUENCE, UUID.
- @Column — column constraints (nullable, length, unique).
Entity relationships:
@Entity
class Order {
@Id @GeneratedValue Long id;
@ManyToOne(fetch = FetchType.LAZY) // many orders belong to one user
@JoinColumn(name = "user_id")
private User user;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private List<OrderItem> items;
}@ManyToOne/@OneToMany— one-to-many (the "many" side holds the FK).@JoinColumn— the foreign key column name.mappedBy— the non-owning side (avoids an extra join table).fetch = LAZY— the recommended default to avoid N+1 (see the N+1 item).
Note: with GenerationType.IDENTITY, Hibernate cannot batch inserts. High-load production often uses SEQUENCE.