Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Spring Boot | How to access database using Spring Data JPA

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 = in order to auto increment the primary key attribute. The following is the implementation of this class:

    public class Company {
        // Primary ID which increments
        // automatically when new entry
        // is added into the database
                        = 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)
   = 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)
   = 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:

    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:

    public class CompanyController {
        private CompanyRepository repo;
        // Home Page
        public String welcome()
            return "<html><body>"
                + "<h1>WELCOME</h1>"
                + "</body></html>";
        // Get All Notes
        public List<Company> getAllNotes()
            return repo.findAll();
        // Get the company details by
        // ID
        public Company getCompanyById(
            @PathVariable(value = "id") int id)
            return repo.findById(id);
        public Company addCompany(
            @RequestBody Company company)
        public void deleteStudent(
            @PathVariable(value = "id") int id)
        public ResponseEntity<Object> updateStudent(
            @RequestBody Company company,
            @PathVariable int id)
            Optional<Company> companyRepo
                = Optional.ofNullable(
            if (!companyRepo.isPresent())
                return ResponseEntity
            return ResponseEntity

  6. Now, open the 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.


  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.


My Personal Notes arrow_drop_up
Last Updated : 10 Jun, 2020
Like Article
Save Article
Similar Reads
Related Tutorials