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. pom.xml - Project Configuration
Add these dependencies in your pom.xml 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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
2. Main Class (StudentCrudApplication.java)
This is the entry point of the Spring Boot application.
@SpringBootApplication
public class StudentCrudApplication {
public static void main(String[] args) {
SpringApplication.run(StudentCrudApplication.class, args);
}
}
3. Student Entity (Student.java)
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 (StudentRepository.java)
This interface allows Spring Data JPA to manage Student data without writing SQL.
public interface StudentRepository extends JpaRepository<Student, Long> {}
5. Controller (StudentController.java)
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 repo.findAll(); }
@PostMapping public Student create(@RequestBody Student s) { return repo.save(s); }
@PutMapping("/{id}") public Student update(@PathVariable Long id, @RequestBody
Student s) {
Student exist = repo.findById(id).orElseThrow();
exist.setName(s.getName()); exist.setCourse(s.getCourse());
return repo.save(exist);
}
@DeleteMapping("/{id}") public String delete(@PathVariable Long id) {
repo.deleteById(id); return "Deleted";
}
}
6. application.properties - Config File
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update