top of page

Spring Boot application that uses Spring Data JPA to connect to a database and perform basic CRUD

  • Writer: Ilakk Manoharan
    Ilakk Manoharan
  • Dec 5, 2022
  • 1 min read

Updated: Jan 4, 2023

Here is an example of a simple Spring Boot application that uses Spring Data JPA to connect to a database and perform basic CRUD (create, read, update, delete) operations:

First, we will create a simple entity class that represents a user:


import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;


@Entity

public class User {

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

private long id;


private String firstName;

private String lastName;

private String email;


// Getters and setters omitted for brevity

}


Next, we will create a repository interface that extends Spring Data JPA's JpaRepository interface and specifies the type of entity and ID that it will be working with:


import org.springframework.data.jpa.repository.JpaRepository;


public interface UserRepository extends JpaRepository<User, Long> {

}


Then, we will create a simple service class that performs basic CRUD operations using the repository:


import org.springframework.stereotype.Service;


@Service

public class UserService {

private final UserRepository userRepository;


public UserService(UserRepository userRepository) {

this.userRepository = userRepository;

}


public List<User> findAll() {

return userRepository.findAll();

}


public User findById(long id) {

return userRepository.findById(id).orElse(null);

}


public User save(User user) {

return userRepository.save(user);

}


public void deleteById(long id) {

userRepository.deleteById(id);

}

}


Finally, we will create a simple controller class that exposes the service's methods as REST endpoints:


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


@RestController

public class UserController {

private final UserService userService;


public UserController(UserService userService) {

this.userService = userService;

}


@GetMapping("/users")

public List<User> findAll() {

return userService.findAll();

}


@GetMapping("/users/{id}")

public User findById(@PathVariable long id) {

return userService.findById(id);

}


@PostMapping("/users")

public User save(@RequestBody User user) {

return userService.save(user);

}


@DeleteMapping("/users/{id}")

public void deleteById(@PathVariable long id) {

userService.deleteById(id);

}

}


To run this application, you will also need to configure a database and add the necessary dependencies to your pom.xml file.

Comments


Drop Me a Line, Let Me Know What You Think

Thanks for submitting!

© 2035 by Train of Thoughts. Powered and secured by Wix

bottom of page