Spring Data JPA – Làm việc với CSDL

Spring Data JPA là gì?

Spring Data JPA là một phần trong hệ sinh thái Spring giúp làm việc với CSDL theo phong cách hướng đối tượng thông qua Java Persistence API (JPA).
Nó cung cấp một lớp trừu tượng trên EntityManager, giúp bạn:

  • Không cần viết SQL thủ công
  • Chỉ cần tạo interface, Spring tự động tạo hàm truy vấn

⚙️ 1️⃣ Thêm dependency vào pom.xml

<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- MySQL Connector -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>

🛠️ 2️⃣ Cấu hình application.properties

# Thông tin kết nối CSDL MySQL
spring.datasource.url=jdbc:mysql://localhost:3306/ql_giangvien?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=your_mysql_password

# JPA / Hibernate
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

🔐 Nhớ thay your_mysql_password bằng mật khẩu MySQL thật của bạn.
🛠 Tạo CSDL ql_giangvien trong MySQL nếu chưa có:

sqlCopyEditCREATE DATABASE ql_giangvien CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

🧱 3️⃣ Entity – GiangVien và DonVi

📄 DonVi.java

@Entity
public class DonVi {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String tenDonVi;

@OneToMany(mappedBy = "donVi")
private List<GiangVien> giangViens;

// Getters và Setters
}

📄 GiangVien.java

@Entity
public class GiangVien {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String hoTen;

@ManyToOne
@JoinColumn(name = "donvi_id")
private DonVi donVi;

// Getters và Setters
}

📦 4️⃣ Repository

public interface DonViRepository extends JpaRepository<DonVi, Long> {
}
public interface GiangVienRepository extends JpaRepository<GiangVien, Long> {
}

🌐 5️⃣ REST Controller đơn giản

@RestController
@RequestMapping("/giangvien")
public class GiangVienController {

@Autowired
private GiangVienRepository giangVienRepo;

@PostMapping
public GiangVien create(@RequestBody GiangVien giangVien) {
return giangVienRepo.save(giangVien);
}

@GetMapping
public List<GiangVien> getAll() {
return giangVienRepo.findAll();
}
}

✅ 6️⃣ Kiểm thử

  • Dùng Postman gửi POST /giangvien:
{
"hoTen": "Trần Thị Lan",
"donVi": {
"id": 1
}
}
  • Tạo trước một DonVi với API riêng (hoặc thêm vào trực tiếp trong MySQL).

✅ Tổng kết

Thành phầnMô tả
spring.datasource.*Cấu hình kết nối MySQL
@EntityÁnh xạ bảng CSDL
@ManyToOne / @OneToManyThiết lập quan hệ giữa các bảng
JpaRepositoryGiao tiếp với CSDL không cần viết SQL thủ công

Comments are closed.