Medicare Doctor CRUD with Spring Data JPA & MySQL

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

  • We already have : spring-boot-starter-web
  • Now add these two dependencies inside <dependencies> in pom.xml:
<!-- 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>
  • After saving pom.xml, Maven should download the dependencies automatically.

Create the database

2

  • If STS doesn't update:

Right Click Project

→ Maven

→ Update Project

  • Open MySQL Workbench and run :
  • Then:
CREATE DATABASE medicare_db;
  • Don't create the doctors table manually.
  • We want Hibernate/JPA to create it from our Java entity.

Configure MySQL

3

  • Open: src/main/resources/application.properties
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_PASSWORD
USE medicare_db;
# JPA / Hibernate Configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
  • Replace: YOUR_MYSQL_PASSWORD with your MySQL password.

 Create Doctor Entity 

4

  • Create package:

com.medicare.entity

  • Then create: Doctor.java
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

  • @Entity means: This Java class represents database data.
  • @Table(name = "doctors") means Hibernate should map this class to doctors table.
  • @Id marks the primary key.
  • @GeneratedValue(strategy = GenerationType.IDENTITY) means MySQL generates IDs automatically.

Create Repository

5

  • Create :

com.medicare.repository

  • Then create: DoctorRepository.java
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> {
}
  • By extending: JpaRepository<Doctor, Long> we automatically get operations such as:
save()
findAll()
findById()
existsById()
deleteById()
  • Meaning Spring Data JPA handles a lot of standard database operations for us.
  • Here: JpaRepository<Doctor, Long> means:
Doctor
   ↓
Entity we're managing

Create Service

6

  • Create Package:
com.medicare.service
  • Then create: DoctorService.java
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;
    }
}
  • The service layer handles: Business Logic
  • For example: public Doctor updateDoctor(...)doesn't simply tell the database to update something.
  • It first:
Find Doctor
    ↓
Does Doctor exist?
    ↓
Update values
    ↓
Save updated Doctor
  • Later, this layer will become responsible for rules such as:
Can this appointment be cancelled?

Is this slot already booked?

Can this doctor create this prescription?

Has payment already been completed?

Constructor Injection

  • Notice: private final DoctorRepository doctorRepository;
  • We're deliberately using constructor injection.
  • We are not going to write:

Create Controller

7

  • Create Package:

com.medicare.controller

  • Then create: DoctorController.java
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

  • Then:

USE medicare_db;

SHOW TABLES;

  • You should see columns similar to:
USE medicare_db;

SHOW TABLES;
DESC doctors;
id
name
specialization
experience_years
consultation_fee
photo_url

Test - CREATE Doctor

9

  • Open Postman
  • Select : POST
  • Enter:
http://localhost:8080/api/doctors
  • Body :

Body

→ raw 

→ JSON

​{
   "name": "Dr. Ananya Sharma",
    "specialization": "Cardiologist",
    "experienceYears": 8,
    "consultationFee": 1200.00,
    "photoUrl": "https://example.com/ananya.jpg"
}
  • Send :

Verify That the Data Was Sent from Postman to MySQL

10

SELECT * FROM doctors;

11

Add few doctors

  • Doctor 2
{
    "name": "Dr. Rohan Mehta",
    "specialization": "Dentist",
    "experienceYears": 5,
    "consultationFee": 700.00,
    "photoUrl": "https://example.com/rohan.jpg"
}
  • Doctor 3
{
    "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"
}
  • Doctor 4

Test GET All Doctors

12

  • Select : GET
  • Enter:
http://localhost:8080/api/doctors

Test GET Doctor by ID

13

  • Select : GET
  • Enter:
http://localhost:8080/api/doctors/1

Test UPDATE Doctor

14

  • Select : PUT
  • Enter:
http://localhost:8080/api/doctors/1
  • Body :
{  
    "name": "Dr. Ananya Sharma",
    "specialization": "Cardiologist",
    "experienceYears": 9,
    "consultationFee": 1300.00,
    "photoUrl": "https://example.com/ananya.jpg"
}

Test DELETE Doctor

15

  • Select : DELETE
  • Enter:
http://localhost:8080/api/doctors/4
  • Current response:
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 branchName

Next-Lab Preparation

Module:

1) Advance Spring data JPA and production ready Rest APi​

SpringBoot Lab - 3

By Content ITV

SpringBoot Lab - 3

  • 502