Spring Boot, create first application using Spring Boot


Spring Boot is an open-source Java-based framework developed by Pivotal (now part of VMware) that makes it easy to create standalone, production-grade Spring applications with minimal configuration

Spring Boot can also be used to develop enterprise applications but we mostly prefer spring boot for API Design.

spring boot is a utility project which aims to make it easy to build spring-based, production-ready applications and services with minimum fuss. it provides the shortest way to get a spring web application up and running with the smallest line of code/configuration out-of-the-box.


✅ Key Features:

FeatureDescription
Auto-ConfigurationAutomatically configures Spring and third-party libraries.
StandaloneNo need for external servers like Tomcat or Jetty — it's embedded.
Production ReadyComes with features like health checks, metrics, logging, etc.
Opinionated DefaultsProvides default configurations to speed up development.
Spring Boot StarterPredefined dependency groups (e.g., spring-boot-starter-web, etc.)
Actuator (optional)Provides monitoring endpoints like /actuator/health, /metrics, etc.
DevTools (optional)Enables auto-reload and hot swapping during development.

✅ Difference Between @Controller and @RestController in Spring Boot

Both @Controller and @RestController are used to define Spring MVC controllers, but they serve different purposes depending on the response type expected by the client.


Feature@Controller@RestController
PurposeUsed for returning web pages (views) like JSP, HTML, ThymeleafUsed for creating RESTful web services / APIs
ReturnsUsually returns a View (String → view name)Returns JSON or XML response (data)
Annotation TypeIt is a generic controllerIt is a specialized version of @Controller
Requires @ResponseBody✅ Yes, you must add @ResponseBody to methods to return JSON/XML❌ No, it is included by default
Use CaseFor web applications with frontend UIFor REST APIs (backend data services)
Example Returnreturn "index"; // returns view namereturn user; // returns 


✅ 1. @SpringBootApplication

  • Purpose: Entry point of any Spring Boot application.

  • Includes: @Configuration, @EnableAutoConfiguration, and @ComponentScan.

  • Used On: Main class.

java

@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }

✅ 2. @RestController

  • Purpose: Marks the class as a REST API controller.

  • Returns: JSON or XML directly in response.

java

@RestController public class CountryController { @GetMapping("/country") public String getCountry() { return "India"; } }

✅ 3. @Autowired

  • Purpose: Automatically injects (wires) dependencies.

  • Used For: Services, repositories, components.

java

@Autowired private CountryService countryService;

✅ 4. @GetMapping / @PostMapping

  • Purpose: Maps HTTP GET/POST requests to methods.

  • Used In: Controller classes.

java

@GetMapping("/country") public Country getCountry() { return new Country("India", "IN"); }

✅ 5. @Entity

  • Purpose: Declares a class as a JPA entity for database mapping.

  • Used In: Model classes.

java

@Entity public class Country { @Id private int id; private String name; }

What is API?

API means an application programming interface that is used to communicate data from application to database server.

API uses HTTP Method to communicate data.

1)  HttpGet:-  to fetch all records from databases  

2)  HttpPost:-  to submit or post record to server from application

3)  HttpPut:-   to replace or edit the record to server from application

4)  HttpDelete:-  to delete record from the server from the application

5)  HttpPatch:-  to partially update the record 

6)  Connect:-  to connect server we can use connect

7)   header:-  to send only header content such as content type, size, and token

What type of result will be returned by API?

API will return JSON as a result, JSON means JavaScript Object Notation, It is used to provide a structured approach to output using key: value pair.

Syntax of JSON for Single row:-

{'key':value}

Syntax of JSON for Multiple rows

{

  [{key:value},{key:value}]

}

all table columns will be worked as a key and table data will work as a value.

spring boot requirements

setting up and running spring boot applications requires the following:

  • java 17+

Create Simple Application using Spring Boot:-

1)   File  ---> New Maven Project  --->Next --> Next

(maven-archetype-quickstart)

2)  Modify pom.xml file only create dependencies 
    <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.springbootpractice</groupId>
  <artifactId>firstspringboot</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <name>firstspringboot</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

   <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.5</version> <!-- Use latest available -->
    <relativePath/> <!-- Required for Spring Boot -->
</parent>

<properties>
    <java.version>21</java.version>
    <spring-boot.version>3.2.5</spring-boot.version>
  </properties>

  <dependencies>

    <!-- ✅ Web dependency for REST APIs + Embedded Tomcat -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Optional: DevTools for auto-restart -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
    </dependency>

    <!-- Optional: Testing -->
    <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>
        <version>${spring-boot.version}</version>
      </plugin>
    </plugins>
  </build>
</project>

3)  Add controller under package
package scs.welcomespring;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@EnableAutoConfiguration
public class WelcomeController {
@RequestMapping("/welcome")
@ResponseBody
public String sayWelcome() {
return "Welcome in Spring Boot Application";
}
}
4)   Create Main Class for Calling
package scs.welcomespring;
import org.springframework.boot.SpringApplication;
public class SpringBootMain {
public static void main(String[] args) {
SpringApplication.run(WelcomeController.class,args);
}
}
Now run the main class method and type the URL 
localhost:8080/welcome



Create Another Controller  

package com.springbootpractice.firstspringboot;

import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.springbootpractice.model.Country;



@RestController
@RequestMapping("/api/countries")
public class CountryController {
private List<Country> countryList = List.of(
        new Country("India", "New Delhi", 1400000000),
        new Country("USA", "Washington, D.C.", 331000000),
        new Country("Japan", "Tokyo", 126000000)
    );
@GetMapping
    public List<Country> getAllCountries() {
        return countryList;
    }
}


package com.springbootpractice.firstspringboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = {
    "com.springbootpractice.model",
    "com.springbootpractice.firstspringboot"
    
})
public class App {
    public static void main(String[] args) {
    SpringApplication.run(App.class,args);
    }
}


✅ What is JPA?

JPA (Java Persistence API) is a specification (not an implementation) for persisting Java objects to a relational database.

  • It defines interfaces and annotations.

  • It is part of Jakarta EE (previously Java EE).

  • It requires an implementation like Hibernate, EclipseLink, or TopLink.

🧠 Think of JPA as a contract.


✅ What is Hibernate?

Hibernate is the most popular implementation of JPA.

  • It is a framework that actually performs the ORM (Object-Relational Mapping).

  • It also provides extra features beyond JPA (like caching, better lazy loading).

🧠 Think of Hibernate as the worker following the JPA contract.


✅ Example: JPA Annotations (Used by Hibernate)


@Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; }

This works in both JPA and Hibernate because Hibernate implements JPA.


✅ Key Differences: JPA vs Hibernate

FeatureJPA (Java Persistence API)Hibernate
TypeSpecificationImplementation of JPA
Provided byJava (Jakarta) EERed Hat (open-source framework)
Requires implementationYes (like Hibernate, EclipseLink)No, it is the implementation
Extra featuresNo (only standard)Yes (caching, validation, interceptors)
Vendor lock-inNoYes, if you use Hibernate-only features
Ease of switching frameworksEasyHard (if tightly coupled to Hibernate)

✅ Which is Better to Use?

Use JPA (with Hibernate):

✔ When you want standard and portable code.
✔ When working in enterprise applications with possible switching of ORM providers.
✔ When using Spring Boot (spring-boot-starter-data-jpa uses Hibernate under the hood by default).

Use Hibernate directly:

✔ When you want advanced features (2nd level caching, filters, native SQL mapping).
✔ When you are okay with Hibernate-specific code.


✅ In Spring Boot?

Always use:

xml

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>

✅ It uses JPA annotations + Hibernate as the default JPA provider.


JPA Query Syntax:


🔶 1. JPQL (Java Persistence Query Language)

JPQL is object-oriented — you write queries using entity class names and fields, not table/column names.

✅ Example 1: Select all students


@Query("SELECT s FROM Student s") List<Student> findAllStudents();

✅ Example 2: Select student by name

j
@Query("SELECT s FROM Student s WHERE s.name = :name") Student findByName(@Param("name") String name);

✅ Example 3: Update student name


@Modifying @Query("UPDATE Student s SET s.name = :name WHERE s.id = :id") void updateStudentName(@Param("id") Long id, @Param("name") String name);

🔶 2. Native SQL Query

Native queries use real SQL, directly on your database tables.

✅ Example: Use actual table and column names

j
@Query(value = "SELECT * FROM students WHERE name = :name", nativeQuery = true) Student findByNameNative(@Param("name") String name);

🔶 3. Derived Query Methods (No @Query needed)

Spring Data JPA can derive queries based on method names.

✅ Example 1: Find by name


Student findByName(String name);

✅ Example 2: Find by name and age


Student findByNameAndAge(String name, int age);

🔶 4. Pagination and Sorting


Page<Student> findByAgeGreaterThan(int age, Pageable pageable); List<Student> findByOrderByNameAsc();

🔶 5. Delete and Count


long countByName(String name); void deleteByName(String name);

Here’s a complete example of a Spring Boot REST API to perform CRUD operations on a Student model.


✅ Step-by-Step Project Structure:


com.example.studentapi ├── Student.java --> Model ├── StudentRepository.java --> Repository ├── StudentController.java --> Controller ├── StudentService.java --> Service ├── StudentServiceImpl.java --> Service Impl └── StudentApiApplication.java --> Main class

✅ 1. pom.xml Dependencies

xml

<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>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies>

✅ 2. Student.java (Model)


package com.example.studentapi.model; import jakarta.persistence.*; @Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // Getters & Setters }

✅ 3. StudentRepository.java

java

package com.example.studentapi.repository; import com.example.studentapi.model.Student; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository<Student, Long> { }

✅ 4. StudentService.java

java

package com.example.studentapi.service; import com.example.studentapi.model.Student; import java.util.List; public interface StudentService { Student saveStudent(Student student); List<Student> getAllStudents(); Student getStudentById(Long id); Student updateStudent(Long id, Student student); void deleteStudent(Long id); }

✅ 5. StudentServiceImpl.java

java

package com.example.studentapi.service; import com.example.studentapi.model.Student; import com.example.studentapi.repository.StudentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentRepository studentRepo; @Override public Student saveStudent(Student student) { return studentRepo.save(student); } @Override public List<Student> getAllStudents() { return studentRepo.findAll(); } @Override public Student getStudentById(Long id) { return studentRepo.findById(id).orElse(null); } @Override public Student updateStudent(Long id, Student updatedStudent) { Student existing = studentRepo.findById(id).orElse(null); if (existing != null) { existing.setName(updatedStudent.getName()); existing.setEmail(updatedStudent.getEmail()); return studentRepo.save(existing); } return null; } @Override public void deleteStudent(Long id) { studentRepo.deleteById(id); } }

✅ 6. StudentController.java

java

package com.example.studentapi.controller; import com.example.studentapi.model.Student; import com.example.studentapi.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/students") public class StudentController { @Autowired private StudentService studentService; @PostMapping public Student createStudent(@RequestBody Student student) { return studentService.saveStudent(student); } @GetMapping public List<Student> getAllStudents() { return studentService.getAllStudents(); } @GetMapping("/{id}") public Student getStudentById(@PathVariable Long id) { return studentService.getStudentById(id); } @PutMapping("/{id}") public Student updateStudent(@PathVariable Long id, @RequestBody Student student) { return studentService.updateStudent(id, student); } @DeleteMapping("/{id}") public String deleteStudent(@PathVariable Long id) { studentService.deleteStudent(id); return "Student deleted successfully!"; } }

✅ 7. application.properties

properties

spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.h2.console.enabled=true spring.jpa.hibernate.ddl-auto=update

✅ 8. StudentApiApplication.java

java

package com.example.studentapi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class StudentApiApplication { public static void main(String[] args) { SpringApplication.run(StudentApiApplication.class, args); } }

✅ Run and Test

  • Run the application.

  • Test endpoints using Postman or curl.


Post a Comment

0 Comments