Content ITV PRO
This is Itvedant Content department
Business Scenario
In this lab, we will extend the Medicare backend by connecting Spring Boot with MySQL using Spring Data JPA.
We will create the Doctor entity, configure the database, and build the Repository, Service, and Controller layers to implement complete CRUD operations.
Finally, we will test creating, retrieving, updating, and deleting doctors using Postman, while understanding how data flows from the API through the application layers to the MySQL database
Pre-Lab Preparation
Module:
1) Introduction to Spring Boot
2) Basic Spring data JPA and Rest APi
Phase 2 — Doctor CRUD Module
Add JPA + MySQL dependencies
1
<!-- Spring Data JPA for database operations -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Database Driver -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connectorj </artifactId>
<scope>runtime</scope>
</dependency>Create the database
2
Right Click Project
→ Maven
→ Update Project
CREATE DATABASE medicare_db;Configure MySQL
3
spring.application.name=medicare-backend
# MySQL Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/medicare_db
spring.datasource.username=root
spring.datasource.password=YOUR_MYSQL_PASSWORDUSE medicare_db;# JPA / Hibernate Configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=trueCreate Doctor Entity
4
com.medicare.entity
package com.medicare.entity;
import java.math.BigDecimal;import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "doctors")
public class Doctor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String specialization;
@Column(name = "experience_years", nullable = false)
private Integer experienceYears;
@Column(
name = "consultation_fee",
nullable = false,
precision = 10,
scale = 2
) public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSpecialization() {
return specialization;
}
public void setSpecialization(String specialization) {
this.specialization = specialization;
}
public Integer getExperienceYears() {
return experienceYears;
}
public void setExperienceYears(Integer experienceYears) {
this.experienceYears = experienceYears;
}
public BigDecimal getConsultationFee() {
return consultationFee;
}
public void setConsultationFee(BigDecimal consultationFee) {
this.consultationFee = consultationFee;
} public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}Understanding Entity
Create Repository
5
com.medicare.repository
package com.medicare.repository;
import org.springframework.data.jpa.repository.JpaRepository;Why BigDecimal for money?
We're using: BigDecimal consultationFee; instead of: double consultationFee; because money should generally use decimal arithmetic rather than floating-point arithmetic.
import com.medicare.entity.Doctor;
public interface DoctorRepository extends JpaRepository<Doctor, Long> {
}save() findAll() findById() existsById() deleteById()
Doctor ↓ Entity we're managing
Create Service
6
com.medicare.service
package com.medicare.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.medicare.entity.Doctor;
import com.medicare.repository.DoctorRepository;
@Service
public class DoctorService {
private final DoctorRepository doctorRepository;
public DoctorService(DoctorRepository doctorRepository) {
this.doctorRepository = doctorRepository;
}
public Doctor createDoctor(Doctor doctor) {
return doctorRepository.save(doctor);
}
public List<Doctor> getAllDoctors() {
return doctorRepository.findAll();
}
public Doctor getDoctorById(Long id) {
return doctorRepository
.findById(id)
.orElse(null);
}
public Doctor updateDoctor(Long id, Doctor doctorDetails) {
Doctor existingDoctor = doctorRepository
.findById(id)
.orElse(null);
if (existingDoctor == null) {
return null;
}
existingDoctor.setName(doctorDetails.getName());
existingDoctor.setSpecialization(
doctorDetails.getSpecialization()
);
existingDoctor.setExperienceYears(
doctorDetails.getExperienceYears()
);
existingDoctor.setConsultationFee(
doctorDetails.getConsultationFee()
);
existingDoctor.setPhotoUrl(
doctorDetails.getPhotoUrl()
);
return doctorRepository.save(existingDoctor);
}
public boolean deleteDoctor(Long id) {
if (!doctorRepository.existsById(id)) {
return false;
}
doctorRepository.deleteById(id);
return true;
}
}Long ↓ Datatype of Doctor's primary key
import com.medicare.repository.DoctorRepository;
@Service
public class DoctorService {
private final DoctorRepository doctorRepository;
public DoctorService(DoctorRepository doctorRepository) {
this.doctorRepository = doctorRepository;
}
public Doctor createDoctor(Doctor doctor) {
return doctorRepository.save(doctor);
}
public List<Doctor> getAllDoctors() {
return doctorRepository.findAll();
}
public Doctor getDoctorById(Long id) {
return doctorRepository
.findById(id)
.orElse(null);
}
public Doctor updateDoctor(Long id, Doctor doctorDetails) { Doctor existingDoctor = doctorRepository
.findById(id)
.orElse(null);
if (existingDoctor == null) {
return null;
}
existingDoctor.setName(doctorDetails.getName());
existingDoctor.setSpecialization(
doctorDetails.getSpecialization()
);
existingDoctor.setExperienceYears(
doctorDetails.getExperienceYears()
);
existingDoctor.setConsultationFee(
doctorDetails.getConsultationFee()
);
existingDoctor.setPhotoUrl(
doctorDetails.getPhotoUrl()
);
return doctorRepository.save(existingDoctor);
}
public boolean deleteDoctor(Long id) {
if (!doctorRepository.existsById(id)) {
return false;
} doctorRepository.deleteById(id);
return true;
}
}Find Doctor ↓ Does Doctor exist? ↓ Update values ↓ Save updated Doctor
Can this appointment be cancelled? Is this slot already booked? Can this doctor create this prescription? Has payment already been completed?
Constructor Injection
Create Controller
7
com.medicare.controller
package com.medicare.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;@Autowired private DoctorRepository doctorRepository;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.medicare.entity.Doctor;
import com.medicare.service.DoctorService;
@RestController
@RequestMapping("/api/doctors")
public class DoctorController {
private final DoctorService doctorService;
public DoctorController(DoctorService doctorService) {
this.doctorService = doctorService;
}
@PostMapping
public Doctor createDoctor(
@RequestBody Doctor doctor) {
return doctorService.createDoctor(doctor);
}
@GetMapping
public List<Doctor> getAllDoctors() {
return doctorService.getAllDoctors();
} @GetMapping("/{id}")
public Doctor getDoctorById(
@PathVariable Long id) {
return doctorService.getDoctorById(id);
}
@PutMapping("/{id}")
public Doctor updateDoctor(
@PathVariable Long id,
@RequestBody Doctor doctor) {
return doctorService.updateDoctor(id, doctor);
}
@DeleteMapping("/{id}")
public String deleteDoctor(
@PathVariable Long id) {
boolean deleted =
doctorService.deleteDoctor(id);
if (deleted) {
return "Doctor deleted successfully";
}
return "Doctor not found";
}
}Start the application
7
Check mysql
8
USE medicare_db;
SHOW TABLES;
USE medicare_db;
SHOW TABLES;DESC doctors;id
name
specialization
experience_years
consultation_fee
photo_urlTest - CREATE Doctor
9
http://localhost:8080/api/doctors
Body
→ raw
→ JSON
{
"name": "Dr. Ananya Sharma",
"specialization": "Cardiologist",
"experienceYears": 8,
"consultationFee": 1200.00,
"photoUrl": "https://example.com/ananya.jpg"
}Verify That the Data Was Sent from Postman to MySQL
10
SELECT * FROM doctors;11
Add few doctors
{
"name": "Dr. Rohan Mehta",
"specialization": "Dentist",
"experienceYears": 5,
"consultationFee": 700.00,
"photoUrl": "https://example.com/rohan.jpg"
}{
"name": "Dr. Priya Nair",
"specialization": "General Physician",
"experienceYears": 10,
"consultationFee": 900.00,
"photoUrl": "https://example.com/priya.jpg"
}{
"name": "Dr. Arjun Kapoor",
"specialization": "Orthopedic",
"experienceYears": 12,
"consultationFee": 1500.00,
"photoUrl": "https://example.com/arjun.jpg"
}Test GET All Doctors
12
http://localhost:8080/api/doctors
Test GET Doctor by ID
13
http://localhost:8080/api/doctors/1
Test UPDATE Doctor
14
http://localhost:8080/api/doctors/1
{
"name": "Dr. Ananya Sharma",
"specialization": "Cardiologist",
"experienceYears": 9,
"consultationFee": 1300.00,
"photoUrl": "https://example.com/ananya.jpg"
}
Test DELETE Doctor
15
http://localhost:8080/api/doctors/4
Doctor deleted successfully
We are done with this lab. The latest source code has been uploaded to GitHub. You can access the latest commit using the link below:
Great job!
You successfully completed the Medicare Doctor CRUD operations with Spring Boot, JPA, and MySQL.
Checkpoint
Git Push
git push origin branchNameNext-Lab Preparation
Module:
1) Advance Spring data JPA and production ready Rest APi
By Content ITV