
Quick Contact
Java Tutorial
- What is Java?
- History of Java
- Hello Java Program
- Features of Java
- Basic Syntax
- Java Setup
- Data Types in Java
- Java Variables
- Operators in Java
- JVM
- Java If-else Statement
- Switch Case Statement
- Java Loops
- Do-While Loop
- Java While Loop
- Continue Statement
- Break Statement in Java
- Constructors in Java
- Oops Concept in Java
- Features of OOPs
- Inheritance
- Exeception handeling
- Aggregation (HAS-A relationship) in Java
- Method Overriding in Java
- Method Overloading
- Java Static Keyword
- Java This Keyword
- Java Final Keyword
- Polymorphism
- Static Binding and Dynamic Binding
- Abstract class in Java
- Access Modifiers in Java
- Difference between abstract class and interface
- Interface in Java
- Garbage Collection in Java
- Java Package
- Encapsulation
- Serialization and Deserialization in Java
- Java Inner Classes
- Java Applets
- Multithreading in Java
- Thread Priorities in Java
- Thread Creation
- Inter Thread Communication
- Wrapper Classes in Java
- Java Input Output
- Java AWT Introduction
- Java Layout Manager
- Java Layout Policy
- Java AWT Events
- Collection Framework
- Collection Framework List Interface
- Swing in Java
- Swing Utility Classes
- Swing Layout Managers
- Java JDBC
- Hibernate Framework Overview – Architecture and Basics
Springboot
- Spring Environment Setup
- Spring Boot CRUD REST API Project using IntelliJ IDEA | Postman | MySQL
- Dockerizing Spring Boot Application | Spring Boot Docker Tutorial
- spring-boot-restapidocumentation with swagger
- Spring Boot HttpClient Overview
- Apache HttpClient POST HTTP Request Example
- Apache HttpClient PUT HTTP Request Example
- Apache HttpClient DELETE HTTP Request Example
- Apache HttpClient HTML Form POST Request Example
- Spring Boot JSP Exampl
- Deploying Spring Boot WAR file with JSP to Tomcat
- Spring Boot Annotations
- Spring Core Annotations
- Spring MVC Annotations with Examples
- Spring Scheduling Annotations
- Spring - Java-based Container Configuration
- Spring Java Based Configuration Example
Hibernate
- Hibernate 5 hello world
- Hibernate- One to One Unidirectional Mapping Annotation Example
- Hibernate - Batch Processing
- Hibernate - Interceptors
- Hibernate 5 - Create, Read, Update and Delete (CRUD) Operations Example
- Hibernate Transaction Management
- Hibernate One to Many Unidirectional Mapping Example
- Hibernate One to Many Bidirectional Mapping Example
- Hibernate Many to Many Annotation Mapping Example
- Hibernate Primary KeyJoin Column
- Hibernate First Level Cache with Example
- Hibernate XML Configuration Example with Maven + Eclipse + MySQL Database
- Hibernate Java Configuration Example
- JPA 2 with Hibernate 5 Bootstrapping Example
- JPA and Hibernate Cascade Types
- Hibernate/JPA - Primary Key Generation
- Hibernate 5 - Enum Type Mapping Example
- Hibernate Component Mapping
- Hibernate Object States – Transient,Persistent and Detached
- Hibernate 5 - Save an Entity Example
- Hibernate 5 - Persist an Entity Example
- Hibernate 5 - saveOrUpdate() Method Example
- Hibernate 5 - get(), load() and byId() Method Examples
- Hibernate 5 - merge() Example
- Hibernate 5 - Delete or Remove an Entity Example
- Hibernate 5 - load() Method Example
- Hibernate Session Interface Methods
- Hibernate Session.clear() Method Example
- Introduction Of Java strutes to Architecture
- Struts 2 - Architecture
- Struts 2 - Configuration Files
- Struts 2 - Actions
- Struts 2 - Interceptors
- Struts 2 - Results & Result Types
- Struts 2 - Value Stack/OGNL
- Struts 2 - File Uploading
- Struts 2 - Database Access
- Struts 2 - Validations Framework
JAVA FX
- JavaFX Tutorial
- Introduction to JavaFX Pane
- JavaFX Popup
- JavaFX group
- JavaFX Controller
- JavaFX Gradient Color
- JavaFXAnchorPane
- JavaFXTabPane
- JavaFX Scene
- JavaFX Stage
- JavaFXWebView
- JavaFX Timeline
- JavaFX Timer
- JavaFX Image
- JavaFX Background
- JavaFX dialog
- JavaFX Font
- JavaFXTextArea
- JavaFXObservableList
- JavaFX GUI
- JavaFX FXML
- JavaFXEventHandler
- JavaFXGradle
- JavafxScrollpane
- JavaFXAPI
Spring Boot CRUD REST API Project using IntelliJ IDEA | Postman | MySQL
Here we will build Spring Boot CRUD REST API Project using IntelliJ IDEA as our IDE. We will use the Postman client to test the REST APIs. We will use Spring Data JPA to develop a repository layer and MySQL database at the backend.
-
-
Create Spring boot application
Spring Boot provides a web tool called Spring Initializer to bootstrap an application quickly. Just go to https://start.spring.io/ and generate a new spring boot project.
Use the below details in the Spring boot creation:
Project Name:
springboot-backend
Project Type:
Maven
Choose dependencies:
Spring Web, Lombok, Spring Data JPA, and MySQL Driver
Package name:
net.ducat.springboot
Packaging:
Jar
Download Spring Boot project as a zip file, unzip it, and import it into IntelliJ IDEA.
Here is the pom.xml file for your reference:
< ?xml version="1.0" encoding="UTF-8"?> < project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> < modelVersion>4.0.0< /modelVersion> < parent> < groupId>org.springframework.boot< /groupId> < artifactId>spring-boot-starter-parent< /artifactId> < version>2.5.5< /version> < relativePath/>< !-- lookup parent from repository --> < /parent> < groupId>net.ducat< /groupId> < artifactId>springboot-backend< /artifactId> < version>0.0.1-SNAPSHOT< /version> < name>springboot-backend< /name> < description>Demo project for Spring Boot REST APIs< /description> < properties> < java.version>11< /java.version> < /properties> < dependencies> < dependency> < groupId>org.springframework.boot< /groupId> < artifactId>spring-boot-starter-data-jpa< /artifactId> < /dependency> < dependency> < groupId>org.springframework.boot< /groupId> < artifactId>spring-boot-starter-web< /artifactId> < /dependency> < dependency> < groupId>mysql< /groupId> < artifactId>mysql-connector-java< /artifactId> < scope>runtime< /scope> < /dependency> < dependency> < groupId>org.projectlombok< /groupId> < artifactId>lombok< /artifactId> < optional>true< /optional> < /dependency> < dependency> < groupId>org.springframework.boot< /groupId> < artifactId>spring-boot-starter-test< /artifactId> < scope>test< /scope> < /dependency> < /dependencies> < build> < plugins> < plugin> < groupId>org.springframework.boot< /groupId> < artifactId>spring-boot-maven-plugin< /artifactId> < configuration> < excludes> < exclude> < groupId>org.projectlombok< /groupId> < artifactId>lombok< /artifactId> < /exclude> < /excludes> < /configuration> < /plugin> < /plugins> < /build> < /project>
-
Create Project or Packaging Structure
create a project or packaging structure for your Spring boot project:
-
Configure MySQL Database
Since we’re using MySQL as our database, we need to configure the database URL, username, and password so that Spring can establish a connection with the database on startup. Open src/main/resources/application.properties file and add the following properties to it:
spring.datasource.url=jdbc:mysql://localhost:3306/ems?useSSL=false spring.datasource.username=root spring.datasource.password=Mysql@123 spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.hibernate.ddl-auto = update
-
Don’t forget to change the spring.datasource.username and spring.datasource.password as per your MySQL installation. Also, create a database named ems in MySQL before proceeding to the next section.
You don’t need to create any tables. The tables will automatically be created by Hibernate from the Employee entity that we will define in the next step. This is made possible by the property spring.jpa.hibernate.ddl-auto = update.
-
Create JPA Entity
Go to model package, create a class named Employee and add the following content into it:
packagenet.ducat.springboot.model; importlombok.AllArgsConstructor; importlombok.Getter; importlombok.NoArgsConstructor; importlombok.Setter; importjavax.persistence.*; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "employees") publicclassEmployee{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "email_id") private String emailId; }
-
Create Spring Data JPA Repository
No, we gonna create a Spring Data JPA repository to talk with the MySQL database.
Go to repository package, create the following EmployeeRepository interface and add the following content to it:
packagenet.ducat.springboot.repository; importnet.ducat.springboot.model.Employee; importorg.springframework.data.jpa.repository.JpaRepository; importorg.springframework.stereotype.Repository; publicinterfaceEmployeeRepositoryextendsJpaRepository<Employee, Long>{ // all crud database methods }
-
Create ResourceNotFoundException Custom Exception
Go to an exception package, create a class named ResourceNotFoundException and add the following content to it:
packagenet.ducat.springboot.exception; importorg.springframework.http.HttpStatus; importorg.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.NOT_FOUND) publicclassResourceNotFoundExceptionextendsRuntimeException{ publicResourceNotFoundException(String message){ super(message); } }
-
Creating Spring Boot CRUD REST APIs
Go to controller package, create a class named EmployeeController and add the following content to it:
packagenet.ducat.springboot.controller; import net.ducat.springboot.exception.ResourceNotFoundException; import net.ducat.springboot.model.Employee; import net.ducat.springboot.repository.EmployeeRepository; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.http.HttpStatus; importorg.springframework.http.ResponseEntity; importorg.springframework.web.bind.annotation.*; importjava.util.List; @CrossOrigin("*") @RestController @RequestMapping("/api/v1/employees") publicclassEmployeeController{ @Autowired privateEmployeeRepositoryemployeeRepository; @GetMapping public List< Employee>getAllEmployees(){ returnemployeeRepository.findAll(); } // build create employee REST API @PostMapping public Employee createEmployee(@RequestBody Employee employee){ returnemployeeRepository.save(employee); } // build get employee by id REST API @GetMapping("{id}") publicResponseEntity< Employee>getEmployeeById(@PathVariablelong id){ Employee employee = employeeRepository.findById(id) .orElseThrow(() ->newResourceNotFoundException("Employee not exist with id:" + id)); returnResponseEntity.ok(employee); } // build update employee REST API @PutMapping("{id}") publicResponseEntity< Employee>updateEmployee(@PathVariablelong id,@RequestBody Employee employeeDetails){ Employee updateEmployee = employeeRepository.findById(id) .orElseThrow(() ->newResourceNotFoundException("Employee not exist with id: " + id)); updateEmployee.setFirstName(employeeDetails.getFirstName()); updateEmployee.setLastName(employeeDetails.getLastName()); updateEmployee.setEmailId(employeeDetails.getEmailId()); employeeRepository.save(updateEmployee); returnResponseEntity.ok(updateEmployee); } // build delete employee REST API @DeleteMapping("{id}") publicResponseEntity< HttpStatus>deleteEmployee(@PathVariablelong id){ Employee employee = employeeRepository.findById(id) .orElseThrow(() ->newResourceNotFoundException("Employee not exist with id: " + id)); employeeRepository.delete(employee); returnnewResponseEntity< >(HttpStatus.NO_CONTENT); } } Get All Employees REST API: @GetMapping public List< Employee>getAllEmployees(){ returnemployeeRepository.findAll(); }
Create Employee REST API:
// build create employee REST API @PostMapping public Employee createEmployee(@RequestBody Employee employee) { returnemployeeRepository.save(employee); }
Get Employee by Id REST API:
// build get employee by id REST API @GetMapping("{id}") publicResponseEntity< Employee>getEmployeeById(@PathVariable long id){ Employee employee = employeeRepository.findById(id) .orElseThrow(() ->newResourceNotFoundException("Employee not exist with id:" + id)); returnResponseEntity.ok(employee); }
Update Employee REST API:
// build update employee REST API @PutMapping("{id}") publicResponseEntity< Employee>updateEmployee(@PathVariablelong id,@RequestBody Employee employeeDetails){ Employee updateEmployee = employeeRepository.findById(id) .orElseThrow(() ->newResourceNotFoundException("Employee not exist with id: " + id)); updateEmployee.setFirstName(employeeDetails.getFirstName()); updateEmployee.setLastName(employeeDetails.getLastName()); updateEmployee.setEmailId(employeeDetails.getEmailId()); employeeRepository.save(updateEmployee); returnResponseEntity.ok(updateEmployee); }
Delete Employee REST API:
// build delete employee REST API @DeleteMapping("{id}") publicResponseEntity< HttpStatus>deleteEmployee(@PathVariable long id){ Employee employee = employeeRepository.findById(id) .orElseThrow(() ->newResourceNotFoundException("Employee not exist with id: " + id)); employeeRepository.delete(employee); returnnewResponseEntity< >(HttpStatus.NO_CONTENT); }
-
Running the Application
We have successfully developed all the CRUD Rest APIs for the Employee model. Now it’s time to deploy our application in a servlet container(embedded tomcat).
Two ways we can start the standalone Spring boot application.
-
- From the root directory of the application and type the following command to run it –
$ mvnspring-boot:run
- From your IDE, run the SpringbootBackendApplication.main() method as a standalone Java class that will start the embedded Tomcat server on port 8080 and point the browser to http://localhost:8080/.
-
-
Testing CRUD REST APIs using Postman
Test Get All Employees REST API:
Test Create Employee REST API:
Test Get Employee By Id REST API:
Test Update Employee REST API:
Test Delete Employee REST API:
Apply now for Advanced Java Training Course