FireBase Crud operation in Spring Boot


                     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 connect our spring boot to firebase. I am going to use maven based configuration.

Here, I am sharing a sample spring boot application with simple crud operation on firebase real-time DB. So, first of all, initialize our application from the 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>

 

Now, list down your configuration value in properties file.

application.yml

fireBase:
  collection: tripLiveTracking
  dbBaseUrl: https://XXXXXX.firebaseio.com
  authFileLocation: xxxxxxxxxxx.adminsdk.json
 
 
Next we have to create a configuration class in out app.

ApplicationConfig.java
 
 
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 data base from our app. You can find that file under firebase console under project overview ->project settings -> service accounts.

 
 
 
  
Now, Create a Controller.

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);
    }
}
 
Here is our LocationService.java
 
 
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();
        }
    }
}
 
Here is simple Employee POJO
 
 
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 thing in action. Feel free to ask any question if you found anything blocking in between the entire blog.

Comments

Popular posts from this blog

Jasper report integration in Spring boot/Spring MVC.

Hybris Overview and b2c installation initialization