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:
- Go to spring initializr and create a new project with the following dependencies:
- 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:
@EntitypublicclassCompany {// Primary ID which increments// automatically when new entry// is added into the database@Id@GeneratedValue(strategy= GenerationType.AUTO)intid;String name;// In monthsintduration;String profile;// Can be 0intstipend;booleanworkFromHome;publicCompany(){}// Parameterized constructorpublicCompany(String name,intduration,String profile,intstipend,booleanworkFromHome){this.name = name;this.duration = duration;this.profile = profile;this.stipend = stipend;this.workFromHome = workFromHome;}// Getters and setters of// the variablespublicintgetId(){returnid;}publicString getName(){returnname;}publicintgetDuration(){returnduration;}publicString getProfile(){returnprofile;}publicintgetStipend(){returnstipend;}publicvoidsetId(intid){this.id = id;}publicbooleanisWorkFromHome(){returnworkFromHome;}chevron_rightfilter_none - 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:
@RepositorypublicinterfaceCompanyRepositoryextendsCrudRepository<Company,Integer> {Company findById(intid);List<Company> findAll();voiddeleteById(intid);}chevron_rightfilter_noneNote: 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:
@RestControllerpublicclassCompanyController {@AutowiredprivateCompanyRepository repo;// Home Page@GetMapping("/")publicString welcome(){return"<html><body>"+"<h1>WELCOME</h1>"+"</body></html>";}// Get All Notes@GetMapping("/company")publicList<Company> getAllNotes(){returnrepo.findAll();}// Get the company details by// ID@GetMapping("/company/{id}")publicCompany getCompanyById(@PathVariable(value ="id")intid){returnrepo.findById(id);}@PostMapping("/company")@ResponseStatus(HttpStatus.CREATED)publicCompany addCompany(@RequestBodyCompany company){returnrepo.save(company);}@DeleteMapping("/delete/{id}")publicvoiddeleteStudent(@PathVariable(value ="id")intid){repo.deleteById(id);}@PutMapping("/company/{id}")publicResponseEntity<Object> updateStudent(@RequestBodyCompany company,@PathVariableintid){Optional<Company> companyRepo= Optional.ofNullable(repo.findById(id));if(!companyRepo.isPresent())returnResponseEntity.notFound().build();company.setId(id);repo.save(company);returnResponseEntity.noContent().build();}chevron_rightfilter_none - 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 - 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:
- The database:
- Testing with the POSTMAN collection:
Recommended Posts:
- Introduction to Spring Boot
- How to create a REST API using Java Spring Boot
- How to create a basic application in Java Spring Boot
- How to encrypt passwords in a Spring Boot project using Jasypt
- Spring Boot | How to publish String messages on Apache Kafka
- Spring Boot | How to publish JSON messages on Apache Kafka
- Containerizing Java applications | Creating a Spring Boot App using Dockerfile
- Introduction to the Spring Data Framework
- Spring MVC with JSP View
- Introduction to Spring Framework
- Spring Dependency Injection with Example
- Spring MVC using Java based configuration
- Bean life cycle in Java Spring
- Aspect Oriented Programming and AOP in Spring Framework
- How to fetch data from Database in PHP PDO using loop ?
- Difference between Database System and Data Warehouse
- Data Management issues in Mobile database
- Differences between Operational Database Systems and Data Warehouse
- How to fetch data from localserver database and display on HTML table using PHP ?
- PHP program to fetch data from localhost server database using XAMPP
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





