0% found this document useful (0 votes)
51 views3 pages

Spring Boot CRUD for Student Management

This document outlines the creation of a simple Spring Boot CRUD application for managing Student entities using an in-memory H2 database. It includes details on project configuration, the main application class, the Student entity, the repository interface, the controller for handling API requests, and the application properties for database configuration. The application supports basic CRUD operations: Create, Read, Update, and Delete for student records.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views3 pages

Spring Boot CRUD for Student Management

This document outlines the creation of a simple Spring Boot CRUD application for managing Student entities using an in-memory H2 database. It includes details on project configuration, the main application class, the Student entity, the repository interface, the controller for handling API requests, and the application properties for database configuration. The application supports basic CRUD operations: Create, Read, Update, and Delete for student records.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Simple Spring Boot CRUD App - Student Management

This is a basic Spring Boot application that performs Create, Read, Update, and Delete
(CRUD) operations
on a Student entity using an in-memory H2 database. It uses Spring Web and Spring Data
JPA.

1. [Link] - Project Configuration

Add these dependencies in your [Link] file to use Spring Boot, Web, JPA, and H2 database:

- spring-boot-starter-web (for building REST APIs)


- spring-boot-starter-data-jpa (for database interaction)
- h2 (in-memory database for testing)

<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>

2. Main Class ([Link])

This is the entry point of the Spring Boot application.


@SpringBootApplication
public class StudentCrudApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}

3. Student Entity ([Link])

This class defines a Student with ID, name, and course. It maps to the database table.

@Entity
public class Student {
@Id @GeneratedValue
private Long id;
private String name;
private String course;
// getters and setters here
}

4. Repository ([Link])

This interface allows Spring Data JPA to manage Student data without writing SQL.

public interface StudentRepository extends JpaRepository<Student, Long> {}

5. Controller ([Link])

This class handles API calls like GET, POST, PUT, and DELETE for students.

@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired StudentRepository repo;

@GetMapping public List<Student> getAll() { return [Link](); }


@PostMapping public Student create(@RequestBody Student s) { return [Link](s); }
@PutMapping("/{id}") public Student update(@PathVariable Long id, @RequestBody
Student s) {
Student exist = [Link](id).orElseThrow();
[Link]([Link]()); [Link]([Link]());
return [Link](exist);
}
@DeleteMapping("/{id}") public String delete(@PathVariable Long id) {
[Link](id); return "Deleted";
}
}

6. [Link] - Config File

[Link]=true
[Link]=jdbc:h2:mem:testdb
[Link]=[Link]
[Link]=sa
[Link]=
[Link]-platform=[Link].H2Dialect
[Link]-auto=update

Common questions

Powered by AI

Configuring the spring.jpa.hibernate.ddl-auto property in application.properties is important because it determines how Hibernate handles database schema management, which is vital for maintaining the integrity and structure of the database schema as the application evolves. Its values range from 'none', 'update', 'create', 'create-drop', to others. In the context of a Spring Boot application like the one described, setting it to 'update' enables Hibernate to automatically create the defined schema by updating the database based on the JPA entity mappings without destroying existing data. This aids in evolutionary database changes during development but requires caution in production environments to avoid unintended data loss .

Using an in-memory database like H2 during development offers several benefits, including fast setup and teardown, which aids in rapid application development cycles. It eliminates the need for an external database, reducing complexity and allowing developers to focus on code functionality. Additionally, it supports testing by allowing the application to store and retrieve data without side effects. However, limitations include the lack of persistence since data is lost when the application stops, making it unsuitable for production environments. H2 may not mimic the behavior of other databases like MySQL or PostgreSQL accurately, which can lead to compatibility issues if not carefully managed .

Annotations such as @Entity, @Id, and @Autowired play crucial roles in the Spring Boot architecture by simplifying configuration and management of components. @Entity marks the Student class as a JPA entity, which is mapped to a database table. It allows Spring to manage and persist instances of this class as rows in the database. @Id specifies the primary key for the entity, critical for ensuring unique identification and operations like updates and deletions. @Autowired simplifies dependency injection, in this case, allowing the StudentController to automatically obtain an instance of StudentRepository, thus enabling repository methods without manual instantiation, promoting loose coupling and easier maintenance .

The StudentCrudApplication class functions as the entry point of the Spring Boot application by utilizing the @SpringBootApplication annotation, which denotes it is a Spring Boot application. The main method in this class calls SpringApplication.run(StudentCrudApplication.class, args) to launch the application. This method sets up the default configuration, starts the Spring application context, and performs a class path scan, among other startup operations .

Enabling the H2 console by setting spring.h2.console.enabled=true and configuring datasource properties like spring.datasource.url and spring.datasource.driverClassName in application.properties enhances development and testing by allowing direct interaction with the in-memory database through a web interface. The URL jdbc:h2:mem:testdb and driver configurations ensure the application uses the correct database connection and driver, facilitating immediate preview and manipulation of data stored during tests. This setup aids in quickly verifying database operations and diagnosing issues in an isolated environment without the overhead of a full external database instance .

The StudentController handles HTTP requests by acting as a REST controller in a Spring Boot application. Annotated with @RestController and @RequestMapping("/students"), it defines endpoints for CRUD operations: GET, POST, PUT, and DELETE. It interacts with the StudentRepository, which is injected using the @Autowired annotation, to perform database operations without implementing the CRUD logic. For instance, GET requests call the repo's findAll to retrieve students, POST requests use save to add new entries, PUT requests modify existing students by fetching with findById and then saving changes, and DELETE requests remove a student by id using deleteById .

The dependencies required in the pom.xml file to implement a basic Spring Boot CRUD application with an in-memory H2 database include spring-boot-starter-web, spring-boot-starter-data-jpa, and h2. The spring-boot-starter-web is necessary for building REST APIs, which allows the application to handle HTTP requests. The spring-boot-starter-data-jpa is needed for database interaction, specifically providing a persistence and transaction management framework. Lastly, the h2 dependency is used for the in-memory database, which is useful for testing because it allows the application to run and store data without needing an external database setup .

The Student entity is mapped to a database table in the Spring Boot application using the @Entity annotation in the Student class. This annotation marks the class as a JPA entity, indicating that it should be mapped to a database table. The @Id annotation marks the 'id' field as the primary key, and @GeneratedValue is used to generate the identifier value automatically. The fields 'name' and 'course' are simple attributes that will correspond to columns in the table named after the class. Thus, each instance of the Student class represents a row in the database table .

In a Spring Boot environment, the main class, StudentCrudApplication, utilizes SpringApplication.run() to initiate the application startup process. This method offers several key functions: it initiates the creation of the Spring application context, performs class path scans and configuration loading, and processes any Spring Boot-specific configurations. By calling SpringApplication.run(StudentCrudApplication.class, args), the bootstrapping functions are invoked automatically, handling dependencies and preparing the application for execution without manual setup .

The StudentRepository interface leverages Spring Data JPA to manage data without explicit SQL queries by extending JpaRepository. This interface provides CRUD operations and query execution capabilities. By extending JpaRepository<Student, Long>, it inherits methods such as findAll, save, findById, and deleteById, which perform common database operations. Spring Data JPA automatically provides implementations for these methods at runtime, eliminating the need to write SQL statements .

You might also like