Firebase CRUD operation using spring boot
Posted By : Gaurav Kumar | 18-Dec-2020
Hello Geeks, hope you are healthy and doing well in this tough time. In this particular blog post, I am going to share the simple way in which you can connect to Google's firebase real-time database. Of course, we will use some of the basic dependencies to connecting out spring boot to the firebase. I am going to use a maven based configuration.
Here, I am sharing a sample spring boot application with with simple crud operation on firebase real-time DB. So, first of all, initialize our application from spring initializer and extract, import the downloaded project into your favorite IDE.
Dependencies I am adding here :
- Spring boot starter web
- Spring firebase admin
Here is my pom.xml.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mobiteam.bookings</groupId> <artifactId>location-service</artifactId> <version>1.0-SNAPSHOT</version> <properties> <spring.boot.version>2.2.2.RELEASE</spring.boot.version> <spring.cloud.version>2.2.2.RELEASE</spring.cloud.version> <lombuk.version>1.18.12</lombuk.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.2.RELEASE</version> <relativePath/> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombuk.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.firebase/firebase-admin --> <dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>6.11.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <finalName>${project.artifactId}</finalName> </build> </project>
Also Read: Spring Boot Application With Zull API Gateway
Now, list down your configuration value in the properties file.
application.yml
fireBase: collection: tripLiveTracking dbBaseUrl: https://XXXXXX.firebaseio.com authFileLocation: xxxxxxxxxxx.adminsdk.json ideaTimeSpanInMinute: 5 liveTrackingIntervalInSecond: 2 googleMap: baseUrl: https://maps.googleapis.com/maps/api/distancematrix/json apiKey: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX mode: bus
package com.techreloded.location.config; @Configuration @Component @Data public class ApplicationConfig { @Value("${fireBase.dbBaseUrl}") private String dbBaseUrl; @Value("${fireBase.collection}") private String collectionName; @Value("${fireBase.authFileLocation}") private String authFileLocation; }
We need a JSON authentication file from firebase which allows us to access our real-time database from our app. You can find that file under the firebase console under project overview ->project settings -> service accounts.
LocationController.java
package com.techreloded.location.controllers; @RestController @RequestMapping("/location") @CrossOrigin("*") public class LocationController { private LocationService locationService; public LocationController(LocationService locationService) { this.locationService = locationService; } @GetMapping( value = "/getEmployee", produces = "application/json") public ResponseEntity<Object> getEmployee(@RequestParam("empId") String empId) throws ExecutionException, InterruptedException { TripTracking tripTracking = locationService.getLiveTrace(empId); if(!StringUtils.isEmpty(employee)){ return ResponseHandler.response(employee,"Current Employee",true,HttpStatus.OK); } return ResponseHandler.response(employee,"Invalid employee Id",false,HttpStatus.NOT_FOUND); }
@PostMapping(value = "/saveEmployee", produces = "application/json")
public ResponseEntity<Object> saveEmployee(@RequestBody Employee employee) throws ExecutionException, InterruptedException { Employee employee = locationService.saveEmployee(employee); return ResponseHandler.response(employee, "Employee stored", true, HttpStatus.OK);
} }
package com.techreloded.location.service; @Service public class LocationService {
private ApplicationConfig applicationConfig; public LocationService(ApplicationConfig applicationConfig) { this.applicationConfig = applicationConfig; } public Employee getEmployee(String tripId) throws ExecutionException, InterruptedException { Firestore dbFirestore = FirestoreClient.getFirestore(); DocumentReference documentReference = dbFirestore.collection(applicationConfig.getCollectionName()).document(tripId); ApiFuture<DocumentSnapshot> future = documentReference.get(); DocumentSnapshot document = future.get(); Employee employee; if(document.exists()) { employee= document.toObject(employee.class); return employee; }else { return null; } }
public Employee saveEmployee(Employee employee)
throws ExecutionException, InterruptedException {
Employee employee = this.getEmployee(employee.getId());
Firestore dbFirestore = FirestoreClient.getFirestore();
ApiFuture<WriteResult> collectionsApiFuture =
dbFirestore.collection(applicationConfig.getCollectionName())
.document(employee.getId()).set(employee);
return employee;
}
return null;
}
@PostConstruct
public void initialize() { try { FileInputStream serviceAccount = new FileInputStream(applicationConfig.getAuthFileLocation()); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) .setDatabaseUrl(applicationConfig.getDbBaseUrl()) .build(); FirebaseApp.initializeApp(options); } catch (Exception e) { e.printStackTrace(); } }
}
package com.techreloded.location.models; @Data @Builder @AllArgsConstructor public class Employee{
private String Id; private String name; private String state; private String age; private String salary; }
Now run the app and tried to see things in action. Feel free to ask any question if you found anything blocking in between the entire blog.
We, at Oodles Technologies, provide full-scale SaaS app development services to build scalable, responsive, and quality-driven web and mobile applications. Contact us for technical assistance or drop us a line at [email protected] for more detail.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Gaurav Kumar
He is always ready to grasp new tech and tools as per project requirement.