- Регистрация
- 1 Мар 2015
- Сообщения
- 1,481
- Баллы
- 155
**If you:
Have doubts about any part of this guide
Find something confusing or unclear
Notice typos/errors
Please reach out in the comments/DMs—I’d be delighted to:
? Clarify concepts
? Fix mistakes promptly
? Improve this resource for everyone
Your feedback helps make this article more accurate and helpful for future readers! **
This project is a Student Management System built as a RESTful API using Spring Boot. It allows you to perform CRUD (Create, Read, Update, Delete) operations on student records, such as:
go to or search "spring initializr" in google
project:maven
language:java
Spring boot:3.4.5 (or any version of your choice)
— Group: use your organization’s domain name(learning.com) in reverse order, e.g., “com.learning.”
— Artifact: give your project an artifact name, e.g., “demo.”
— Name: enter a name for your project, e.g., “SpringBootDemo.”
— Description: this field is optional.
— Package name: define your base package automatically generated you can also change it but it is combo of group and artifact , e.g., “com.learning.demo.”
— Packaging: choose “Jar” for a standalone JAR file.
java:21
Dependencies:
Now click on Generate which will generate a zip ,extract it and open in IDE
My project name is smartcampus so it creates an folder with the same name
inside it you will find "src" folder under it "main" under it "java"
-->smartcampus
|->src
|->main
|->java
|->com.sc.smartcampus
|->resources
Entity
So to start we need to have a Object that will be stored in Database we call it "Entity". Purpose: Map to database table.
Create an model folder named "model" under com.sc.smartcampus here all Your Entity will be stored
We are going to create an Student entity.
model
|->Student.java
@Entity // says this is an Entity
@Table(name="students") //It will create an Table with the name students
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String department;
private LocalDate enrollmentDate;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", department='" + department + '\'' +
", enrollmentDate=" + enrollmentDate +
'}';
}
-->generate Getter ,Setter and All argument constructor and no argument constructor
-->can do this manually ,lombok or right click on your ide you can see generate Getter,setter and constructor not all ide have this
}
So we create an students table with the following coloum id,name,email,department and enrollmentDate.
repository
Now we have create an Entity, to perform some operation to the database we need something called repository.
Now we will create an repository folder as we are using Student entity we call it StudentRepository (interface)
public interface StudentRepository extends JpaRepository<Student, Long>{
}
Student
The entity class this repository manages (your @Entity class)
All operations will work with Student objects
Long
The type of the entity's ID field (student.id)
Must match the field type in your Student class
DTO
DTOs keep your API safe and flexible by controlling what data gets exposed, separate from your database structure.
dto
|->Studentdto
It is the same as the model we have created
public class StudentDto {
private String name;
private String email;
private String department;
private LocalDate enrollmentDate;
//getter,setter and no args,all args .
}
here no need for or @Entity as we are not creating an table for the database
what we are doing is that when we create an API request or response we need to store that ,so we are creating Dto.
service
List all the service function we are going to do
service
|->StudentService
public interface StudentService {
StudentDto createStudent(StudentDto dto);
List<StudentDto> getAllStudents();
StudentDto getStudentById(Long id);
StudentDto updateStudent(Long id, StudentDto dto);
void deleteStudent(Long id);
}
service
|->StudentService
|->impl
|->StudentServiceImpl.java
Inside StudentServiceImpl we are going to implement all the service we listed in *StudentService * we need to use @Service
but as i have told dto data and database data cannot be transfer directly
so create
private StudentDto mapToDto(Student student) {
return new StudentDto(
student.getName(),
student.getEmail(),
student.getDepartment(),
student.getEnrollmentDate()
);
}
Gets Student data[database data and convert to Dto]
private Student mapToEntity(StudentDto dto) {
Student student = new Student();
student.setName(dto.getName());
student.setEmail(dto.getEmail());
student.setDepartment(dto.getDepartment());
student.setEnrollmentDate(dto.getEnrollmentDate());
return student;
}
Gets Student Dto[Dto data to database data]
** to use database and operation**
->
private final StudentRepository repository;
public StudentServiceImpl(StudentRepository repository) {
this.repository = repository;
}
we get like this
@Service
public class StudentServiceImpl implements StudentService {
private final StudentRepository repository;
public StudentServiceImpl(StudentRepository repository) {
this.repository = repository;
}
private StudentDto mapToDto(Student student) {
return new StudentDto(
student.getName(),
student.getEmail(),
student.getDepartment(),
student.getEnrollmentDate()
);
}
private Student mapToEntity(StudentDto dto) {
Student student = new Student();
student.setName(dto.getName());
student.setEmail(dto.getEmail());
student.setDepartment(dto.getDepartment());
student.setEnrollmentDate(dto.getEnrollmentDate());
return student;
}}
we will override createStudent,getAllStudents,getStudentById,updateStudent,deleteStudent
@Override
public StudentDto createStudent(StudentDto dto) {
Student saved = repository.save(mapToEntity(dto));
return mapToDto(saved);
}
We are taking Dto as input in createStudent.We hould convert it into entity so that we can save it into database.
mapToEntity(dto)-->convert dto into entity
repository.save()-->saves the entity into database
mapToDto()-->conveting the entity to dto data
@Override
public List<StudentDto> getAllStudents() {
return repository.findAll().stream()
.map(this::mapToDto)
.collect(Collectors.toList());
}
we are taking all the data from database and coverting each into Dto and returning it as list
@Override
public StudentDto getStudentById(Long id) {
Student student = repository.findById(id)
.orElseThrow(() -> new RuntimeException("Student not found with ID: " + id));
return mapToDto(student);
}
we are finding the Student by id in repository and the return the student via mapToDto
@Override
public StudentDto updateStudent(Long id, StudentDto dto) {
Student student = repository.findById(id)
.orElseThrow(() -> new RuntimeException("Student not found with ID: " + id));
student.setName(dto.getName());
student.setEmail(dto.getEmail());
student.setDepartment(dto.getDepartment());
student.setEnrollmentDate(dto.getEnrollmentDate());
return mapToDto(repository.save(student));
}
we are finding the student by id and we are also taking dto as input to update the student detail.
after setting all the student detail in database we are sending it back as an Dto data
@Override
public void deleteStudent(Long id) {
if (!repository.existsById(id)) {
throw new RuntimeException("Student not found with ID: " + id);
}
repository.deleteById(id);
}
delete an student by id
*controller *
We have now Entity ,Dto, Repository and service
now we need controller which will give us dto request and respose
controller
|->StudentController.java
we need @RestController-->say it is an controller
@RequestMapping("/api/students")-->putting up a signboard for your API
we also need StudentService to do all the service listed there
private final StudentService studentService;
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
First of all we are using @PostMapping to post an request
here we are using @RequestBody StudentDto dto. The json we are give will be converted to dto type
and then we are using that dto and we are creating student by the method of studentService.createStudent(dto)
and then we send an response by saying it is created
@PostMapping(consumes = "application/json", produces = "application/json")
public ResponseEntity<StudentDto> createStudent(@RequestBody StudentDto dto) {
StudentDto created = studentService.createStudent(dto);
return new ResponseEntity<>(created, HttpStatus.CREATED);
}
to get all student
@GetMapping(produces = "application/json")
public ResponseEntity<List<StudentDto>> getAllStudents() {
return ResponseEntity.ok(studentService.getAllStudents());
}
to get by id
@GetMapping(value = "/{id}", produces = "application/json")
public ResponseEntity<StudentDto> getStudentById(@PathVariable Long id) {
return ResponseEntity.ok(studentService.getStudentById(id));
}
to update
@PutMapping(value = "/{id}", consumes = "application/json", produces = "application/json")
public ResponseEntity<StudentDto> updateStudent(@PathVariable Long id, @RequestBody StudentDto dto) {
return ResponseEntity.ok(studentService.updateStudent(id, dto));
}
to delete
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
return ResponseEntity.noContent().build();
}
@PathVariable - "Read from URL"
Grabs numbers/words from the web address
@RequestBody - "Get JSON from Request"
What it does: Takes the JSON data sent in the request and automatically converts it to a Java object
Database
-->smartcampus
|->src
|->main
|->java
|->com.sc.smartcampus
|->resources
|->application.properties
go to application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/database_name
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
server.port=9090 --->here i have mentioned to start spring boot at port no 9090
Have doubts about any part of this guide
Find something confusing or unclear
Notice typos/errors
Please reach out in the comments/DMs—I’d be delighted to:
? Clarify concepts
? Fix mistakes promptly
? Improve this resource for everyone
Your feedback helps make this article more accurate and helpful for future readers! **
This project is a Student Management System built as a RESTful API using Spring Boot. It allows you to perform CRUD (Create, Read, Update, Delete) operations on student records, such as:
- Adding new students
- Retrieving student details
- Updating student information
- Deleting stuor dent records
go to or search "spring initializr" in google
project:maven
language:java
Spring boot:3.4.5 (or any version of your choice)
— Group: use your organization’s domain name(learning.com) in reverse order, e.g., “com.learning.”
— Artifact: give your project an artifact name, e.g., “demo.”
— Name: enter a name for your project, e.g., “SpringBootDemo.”
— Description: this field is optional.
— Package name: define your base package automatically generated you can also change it but it is combo of group and artifact , e.g., “com.learning.demo.”
— Packaging: choose “Jar” for a standalone JAR file.
java:21
Dependencies:
- Spring Web
- Spring data JPA
- Mysql driver
Now click on Generate which will generate a zip ,extract it and open in IDE
My project name is smartcampus so it creates an folder with the same name
inside it you will find "src" folder under it "main" under it "java"
-->smartcampus
|->src
|->main
|->java
|->com.sc.smartcampus
|->resources
Entity
So to start we need to have a Object that will be stored in Database we call it "Entity". Purpose: Map to database table.
Create an model folder named "model" under com.sc.smartcampus here all Your Entity will be stored
We are going to create an Student entity.
model
|->Student.java
@Entity // says this is an Entity
@Table(name="students") //It will create an Table with the name students
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String department;
private LocalDate enrollmentDate;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", department='" + department + '\'' +
", enrollmentDate=" + enrollmentDate +
'}';
}
-->generate Getter ,Setter and All argument constructor and no argument constructor
-->can do this manually ,lombok or right click on your ide you can see generate Getter,setter and constructor not all ide have this
}
So we create an students table with the following coloum id,name,email,department and enrollmentDate.
repository
Now we have create an Entity, to perform some operation to the database we need something called repository.
Now we will create an repository folder as we are using Student entity we call it StudentRepository (interface)
public interface StudentRepository extends JpaRepository<Student, Long>{
}
Student
The entity class this repository manages (your @Entity class)
All operations will work with Student objects
Long
The type of the entity's ID field (student.id)
Must match the field type in your Student class
DTO
DTOs keep your API safe and flexible by controlling what data gets exposed, separate from your database structure.
dto
|->Studentdto
It is the same as the model we have created
public class StudentDto {
private String name;
private String email;
private String department;
private LocalDate enrollmentDate;
//getter,setter and no args,all args .
}
here no need for or @Entity as we are not creating an table for the database
what we are doing is that when we create an API request or response we need to store that ,so we are creating Dto.
service
List all the service function we are going to do
service
|->StudentService
public interface StudentService {
StudentDto createStudent(StudentDto dto);
List<StudentDto> getAllStudents();
StudentDto getStudentById(Long id);
StudentDto updateStudent(Long id, StudentDto dto);
void deleteStudent(Long id);
}
service
|->StudentService
|->impl
|->StudentServiceImpl.java
Inside StudentServiceImpl we are going to implement all the service we listed in *StudentService * we need to use @Service
but as i have told dto data and database data cannot be transfer directly
so create
private StudentDto mapToDto(Student student) {
return new StudentDto(
student.getName(),
student.getEmail(),
student.getDepartment(),
student.getEnrollmentDate()
);
}
Gets Student data[database data and convert to Dto]
private Student mapToEntity(StudentDto dto) {
Student student = new Student();
student.setName(dto.getName());
student.setEmail(dto.getEmail());
student.setDepartment(dto.getDepartment());
student.setEnrollmentDate(dto.getEnrollmentDate());
return student;
}
Gets Student Dto[Dto data to database data]
** to use database and operation**
->
private final StudentRepository repository;
public StudentServiceImpl(StudentRepository repository) {
this.repository = repository;
}
we get like this
@Service
public class StudentServiceImpl implements StudentService {
private final StudentRepository repository;
public StudentServiceImpl(StudentRepository repository) {
this.repository = repository;
}
private StudentDto mapToDto(Student student) {
return new StudentDto(
student.getName(),
student.getEmail(),
student.getDepartment(),
student.getEnrollmentDate()
);
}
private Student mapToEntity(StudentDto dto) {
Student student = new Student();
student.setName(dto.getName());
student.setEmail(dto.getEmail());
student.setDepartment(dto.getDepartment());
student.setEnrollmentDate(dto.getEnrollmentDate());
return student;
}}
we will override createStudent,getAllStudents,getStudentById,updateStudent,deleteStudent
@Override
public StudentDto createStudent(StudentDto dto) {
Student saved = repository.save(mapToEntity(dto));
return mapToDto(saved);
}
We are taking Dto as input in createStudent.We hould convert it into entity so that we can save it into database.
mapToEntity(dto)-->convert dto into entity
repository.save()-->saves the entity into database
mapToDto()-->conveting the entity to dto data
@Override
public List<StudentDto> getAllStudents() {
return repository.findAll().stream()
.map(this::mapToDto)
.collect(Collectors.toList());
}
we are taking all the data from database and coverting each into Dto and returning it as list
@Override
public StudentDto getStudentById(Long id) {
Student student = repository.findById(id)
.orElseThrow(() -> new RuntimeException("Student not found with ID: " + id));
return mapToDto(student);
}
we are finding the Student by id in repository and the return the student via mapToDto
@Override
public StudentDto updateStudent(Long id, StudentDto dto) {
Student student = repository.findById(id)
.orElseThrow(() -> new RuntimeException("Student not found with ID: " + id));
student.setName(dto.getName());
student.setEmail(dto.getEmail());
student.setDepartment(dto.getDepartment());
student.setEnrollmentDate(dto.getEnrollmentDate());
return mapToDto(repository.save(student));
}
we are finding the student by id and we are also taking dto as input to update the student detail.
after setting all the student detail in database we are sending it back as an Dto data
@Override
public void deleteStudent(Long id) {
if (!repository.existsById(id)) {
throw new RuntimeException("Student not found with ID: " + id);
}
repository.deleteById(id);
}
delete an student by id
*controller *
We have now Entity ,Dto, Repository and service
now we need controller which will give us dto request and respose
controller
|->StudentController.java
we need @RestController-->say it is an controller
@RequestMapping("/api/students")-->putting up a signboard for your API
we also need StudentService to do all the service listed there
private final StudentService studentService;
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
First of all we are using @PostMapping to post an request
here we are using @RequestBody StudentDto dto. The json we are give will be converted to dto type
and then we are using that dto and we are creating student by the method of studentService.createStudent(dto)
and then we send an response by saying it is created
@PostMapping(consumes = "application/json", produces = "application/json")
public ResponseEntity<StudentDto> createStudent(@RequestBody StudentDto dto) {
StudentDto created = studentService.createStudent(dto);
return new ResponseEntity<>(created, HttpStatus.CREATED);
}
to get all student
@GetMapping(produces = "application/json")
public ResponseEntity<List<StudentDto>> getAllStudents() {
return ResponseEntity.ok(studentService.getAllStudents());
}
to get by id
@GetMapping(value = "/{id}", produces = "application/json")
public ResponseEntity<StudentDto> getStudentById(@PathVariable Long id) {
return ResponseEntity.ok(studentService.getStudentById(id));
}
to update
@PutMapping(value = "/{id}", consumes = "application/json", produces = "application/json")
public ResponseEntity<StudentDto> updateStudent(@PathVariable Long id, @RequestBody StudentDto dto) {
return ResponseEntity.ok(studentService.updateStudent(id, dto));
}
to delete
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
return ResponseEntity.noContent().build();
}
@PathVariable - "Read from URL"
Grabs numbers/words from the web address
@RequestBody - "Get JSON from Request"
What it does: Takes the JSON data sent in the request and automatically converts it to a Java object
Database
-->smartcampus
|->src
|->main
|->java
|->com.sc.smartcampus
|->resources
|->application.properties
go to application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/database_name
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
server.port=9090 --->here i have mentioned to start spring boot at port no 9090