Cloud/Firebase

Firebase(firestore) - 자바에서 컬렉션과 도큐먼트를 다루는 방법

개봉박살 2021. 3. 27. 23:31

파이어베이스 SDK 초기화

public void initialize(){
    try{
        //키파일 로드
        FileInputStream firebase_private_key= new FileInputStream("키파일.json");

        //파이어베이스 키 인증
        GoogleCredentials credentials = GoogleCredentials.fromStream(firebase_private_key);
        FirebaseOptions options = new FirebaseOptions.Builder()
                                         .setCredentials(credentials)
                                         .build();

        //파이어베이스SDK 초기화
        FirebaseApp.initializeApp(options);
        log.info("\t Firebase initialize complete - ");

    }catch(IllegalStateException e){
        log.error(e.getMessage());
    }catch(Exception e){
        e.printStackTrace();
    }
}

FirebaseApp.initializeApp(options);를 수행하면 프로세스 내에 파이어베이스클라이언트 클래스의 인스턴스가 생성된다.
파이어베이스 클라이언트는 싱글톤으로 인스턴스가 생성되어서 프로세스내부에서 언제든지 인스턴스를 가져올수있다.

파이어스토어 - 컬렉션과 도큐먼트

파이어스토어

파이어스토어는 파이어베이스에서 제공하는 NoSql형식의 데이터베이스이다. 파이어베이스 콘솔에 접속해서 파이어스토어를 구성을 보면 단계는 다음과 같다.

기본 구조  
  컬렉션  
    └ 도큐먼트  
        └ 필드 : 데이터

기본구조와 같이 최상위에 컬렉션이 있고 그밑에 도큐먼트가있다 그리고 그밑에 드디어 데이터를 저장할 수 있다.
그리고 도큐먼트 밑에 다시 컬렉션부터 다시 포함시킬 수 있다.

확장 구조  
  컬렉션  
    └ 도큐먼트  
        ├ 필드 : 데이터  
        └ 컬렉션  
            └ 도큐먼트  
            └ 필드 : 데이터

이렇게 얼마든지 데이터를 확장시킬 수 있다. 때문에 NoSQL의 특성을 가지고 있으며, 데이터를 다룰때 정확한 구조를 알고 사용해야 한다는 단점이 있지만 형식에 얽매이지 않을수있다.
참...좋지만 나쁘다.....

파이어스토어 데이터 가져오기

위에서 초기화한 파이어베이스SDK의 싱글턴인스턴스를 가져와서 파이어스토어의 데이터를 가져올 수 있다.
아래 코드는 파이어스토어의 데이터를 콘솔창에 출력하는 코드이다.

Firestore firestore = FirestoreClient.getFirestore();

Iterator<CollectionReference> collections = firestore.listCollections().iterator();
Iterator<DocumentReference> documents = null;

while(collections.hasNext()){
    CollectionReference collection = collections.next();    //콜렉션 가져오기

    String collection_id = collection.getId();                //콜렉션 ID 가져오기
    System.out.println("-------------------------------------");
    System.out.println("Collection ID : "+collection_id);

    documents = collection.listDocuments().iterator();        //콜렉션에 포함된 도큐먼트 가져오기

    while(documents.hasNext()){
        DocumentReference documentReference = documents.next();
        String document_id = documentReference.getId();        // 도큐먼트 ID가져오기
        System.out.println("\t- Document ID : "+document_id);

        ApiFuture<DocumentSnapshot> apiFuture = documentReference.get();    //필드와 벨류값을 다루는 클래스(스냅샷)
        DocumentSnapshot snapshot = apiFuture.get();

        System.out.println("\t\t --------- field : value ---------");

       /**
           * 람다
        * 1. Objects.requireNonNull()메서드로 null체크
        * 2. null이 아니면 forEach문 실행
        * 3. 필드명과 데이터 출력
       */ 
       Objects.requireNonNull(snapshot.getData()).forEach((key, value)->System.out.println("\t\t - "+key + " : " + value));
    }
}

위는 파이어베이스 내부에 컬렉션과 도큐먼트의 리스트를 가져와서 한번씩 전부 출력하는 로직이다.
하지만 사실은 개발할때는 모든 이름을 알고있으므로 아래와 같이 사용하면된다.

DocumentReference documentReference = firestore.collection("콜렉션아이디").document("도큐먼트아이디");