Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaSpring Boot | How to access database using Spring Data JPA

Spring Boot | How to access database using Spring Data JPA

Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot application using spring data JPA.

Inorder to learn how to create a spring boot project, refer this article.

A database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. So, for any application, database is one of the most important modules and there needs to be a way to communicate with it. Therefore, the following steps are followed in order to access the database using Spring Data JPA:

  1. Go to spring initializr and create a new project with the following dependencies:
    • Spring Web
    • Spring Data JPA
    • MySQL Driver
  2. Download the starter project and import it in the IDE.
  3. After the project syncs, we will create a model class Company with the annotation @Entity which means that this class is mapped to the table in the database. Add the data members with the data types the same as the columns in the database and generate constructor and getters. Add the annotation @Id to the data member which will behave as the primary key attribute in the table and @Generatedvalue(strategy = generationtype.auto) in order to auto increment the primary key attribute. The following is the implementation of this class:




    @Entity
    public class Company {
      
        // Primary ID which increments
        // automatically when new entry
        // is added into the database
        @Id
        @GeneratedValue(strategy
                        = GenerationType.AUTO)
        int id;
      
        String name;
      
        // In months
        int duration;
        String profile;
      
        // Can be 0
        int stipend;
        boolean workFromHome;
      
        public Company()
        {
        }
      
        // Parameterized constructor
        public Company(String name, int duration,
                       String profile,
                       int stipend,
                       boolean workFromHome)
        {
            this.name = name;
            this.duration = duration;
            this.profile = profile;
            this.stipend = stipend;
            this.workFromHome = workFromHome;
        }
      
        // Getters and setters of
        // the variables
        public int getId()
        {
            return id;
        }
      
        public String getName()
        {
            return name;
        }
      
        public int getDuration()
        {
            return duration;
        }
      
        public String getProfile()
        {
            return profile;
        }
      
        public int getStipend()
        {
            return stipend;
        }
      
        public void setId(int id)
        {
            this.id = id;
        }
      
        public boolean isWorkFromHome()
        {
            return workFromHome;
        }

    
    
  4. Now, create an interface CompanyRepository with the annotation @Repository which will implement the CrudRepository. The functions to perform the CRUD operations will be defined in the interface as shown below:




    @Repository
    public interface CompanyRepository
        extends CrudRepository<Company,
                               Integer> {
      
        Company findById(int id);
        List<Company> findAll();
        void deleteById(int id);
    }

    
    

    Note: The functions won’t be implemented as they are already implemented in the CrudRepository.

  5. Now, we will create REST APIs(GET, POST, PUT, DELETE) as shown below:




    @RestController
    public class CompanyController {
        @Autowired
        private CompanyRepository repo;
      
        // Home Page
        @GetMapping("/")
        public String welcome()
        {
            return "<html><body>"
                + "<h1>WELCOME</h1>"
                + "</body></html>";
        }
      
        // Get All Notes
        @GetMapping("/company")
        public List<Company> getAllNotes()
        {
            return repo.findAll();
        }
      
        // Get the company details by
        // ID
        @GetMapping("/company/{id}")
        public Company getCompanyById(
            @PathVariable(value = "id") int id)
        {
            return repo.findById(id);
        }
      
        @PostMapping("/company")
        @ResponseStatus(HttpStatus.CREATED)
        public Company addCompany(
            @RequestBody Company company)
        {
            return repo.save(company);
        }
      
        @DeleteMapping("/delete/{id}")
        public void deleteStudent(
            @PathVariable(value = "id") int id)
        {
            repo.deleteById(id);
        }
      
        @PutMapping("/company/{id}")
        public ResponseEntity<Object> updateStudent(
            @RequestBody Company company,
            @PathVariable int id)
        {
      
            Optional<Company> companyRepo
                = Optional.ofNullable(
                    repo.findById(id));
      
            if (!companyRepo.isPresent())
                return ResponseEntity
                    .notFound()
                    .build();
      
            company.setId(id);
      
            repo.save(company);
      
            return ResponseEntity
                .noContent()
                .build();
        }

    
    
  6. Now, open the application.properties file and add the following code. Replace the database_name with the database containing the table Company, username with the username of mysql server(default is root) and password with the mysql password.

    spring.datasource.url=jdbc:mysql://localhost:3306/database_name
    spring.datasource.username=username
    spring.datasource.password=password
    spring.jpa.hibernate.ddl-auto=update

  7. This completes the process of establishing a connection with the database. Now, we build and run the project and call the different APIs.

    Note: Postman is usually preferred to test call APIs, hence we have used the postman tool to test the project.

Output:

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments