Spring Boot | How to access database using Spring Data JPA

10 Jun, 2020
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:
Go to spring initializr and create a new project with the following dependencies:Spring WebSpring Data JPAMySQL DriverDownload the starter project and import it in the IDE.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:@Entitypublic 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;    }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:@Repositorypublic 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.Now, we will create REST APIs(GET, POST, PUT, DELETE) as shown below:@RestControllerpublic 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();    }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_namespring.datasource.username=usernamespring.datasource.password=passwordspring.jpa.hibernate.ddl-auto=updateThis 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.
Go to spring initializr and create a new project with the following dependencies:Spring WebSpring Data JPAMySQL Driver
Spring Web
Spring Data JPA
MySQL Driver
Download the starter project and import it in the IDE.
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:@Entitypublic 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;    }
@Entitypublic 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;    }
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:@Repositorypublic 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.
@Repositorypublic 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.
Now, we will create REST APIs(GET, POST, PUT, DELETE) as shown below:@RestControllerpublic 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();    }
@RestControllerpublic 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();    }
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_namespring.datasource.username=usernamespring.datasource.password=passwordspring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/database_namespring.datasource.username=usernamespring.datasource.password=passwordspring.jpa.hibernate.ddl-auto=update
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.
Note: Postman is usually preferred to test call APIs, hence we have used the postman tool to test the project.
Output:
The database:
Testing with the POSTMAN collection:
java-advanced
Java-Spring
mysql
DBMS
Java
Web Technologies
Java
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.