* 프레임워크 : Spring Boot
* 프로젝트 : Gradle
* 데이터베이스 : firebase의 firestore
[결과]
[ Firestore ]
우선 파이어스토어에 다음과 같이 데이터를 넣는다.
(문서ID를 FMgoGDQHyNQ7IfGycZ0h 이런 식으로 설정 할 필요는 없습니다!
제가 잘 모르고 자동완성ID를 한거에요ㅠ)
[ spring 코드 ]
controller / Restcontroller.java
package DSC4.cafein.controller;
import DSC4.cafein.domain.Member;
import DSC4.cafein.service.FirebaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@org.springframework.web.bind.annotation.RestController
public class RestController {
@Autowired
FirebaseService firebaseService;
@GetMapping("/insertMember")
public String insertMember(@RequestParam Member member) throws Exception{
return firebaseService.insertMember(member);
}
@GetMapping("/getMemberDetail")
public Member getMemberDetail(@RequestParam String id) throws Exception{
return firebaseService.getMemberDetail(id);
}
@GetMapping("/updateMember")
public String updateMember(@RequestParam Member member) throws Exception{
return firebaseService.updateMember(member);
}
@GetMapping("/deleteMember")
public String deleteMember(@RequestParam String id) throws Exception{
return firebaseService.deleteMember(id);
}
}
domain / Member.java
package DSC4.cafein.domain;
public class Member {
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String email;
private String username;
private String id;
private String password;
}
service / FirebaseService.java
package DSC4.cafein.service;
import DSC4.cafein.domain.Member;
public interface FirebaseService {
public String insertMember(Member member) throws Exception;
public Member getMemberDetail(String id) throws Exception;
public String updateMember(Member member) throws Exception;
public String deleteMember(String id) throws Exception;
}
service / FirebaseServiceImpl.java
package DSC4.cafein.service;
import DSC4.cafein.domain.Member;
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.DocumentReference;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.WriteResult;
import com.google.firebase.cloud.FirestoreClient;
import org.springframework.stereotype.Service;
@Service
public class FirebaseServiceImpl implements FirebaseService{
public static final String COLLECTION_NAME = "Member";
@Override
public String insertMember(Member member) throws Exception{
Firestore firestore = FirestoreClient.getFirestore();
ApiFuture<com.google.cloud.firestore.WriteResult> apiFuture =
firestore.collection(COLLECTION_NAME).document(member.getId()).set(member);
return apiFuture.get().getUpdateTime().toString();
}
@Override
public Member getMemberDetail(String id) throws Exception {
Firestore firestore = FirestoreClient.getFirestore();
DocumentReference documentReference =
firestore.collection(COLLECTION_NAME).document(id);
ApiFuture<DocumentSnapshot> apiFuture = documentReference.get();
DocumentSnapshot documentSnapshot = apiFuture.get();
Member member = null;
if(documentSnapshot.exists()){
member = documentSnapshot.toObject(Member.class);
return member;
}
else{
return null;
}
}
@Override
public String updateMember(Member member) throws Exception {
Firestore firestore = FirestoreClient.getFirestore();
ApiFuture<com.google.cloud.firestore.WriteResult> apiFuture
= firestore.collection(COLLECTION_NAME).document(member.getId()).set(member);
return apiFuture.get().getUpdateTime().toString();
}
@Override
public String deleteMember(String id) throws Exception {
Firestore firestore = FirestoreClient.getFirestore();
ApiFuture<WriteResult> apiFuture
= firestore.collection(COLLECTION_NAME).document(id).delete();
return "Document id: "+id+" delete";
}
}
service / FirebaseInitializer.java
package DSC4.cafein.service;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.swing.tree.ExpandVetoException;
import java.io.FileInputStream;
@Service
public class FirebaseInitializer {
@PostConstruct
public void initialize(){
try{
FileInputStream serviceAccount=
new FileInputStream("./src/main/resources/serviceAccountKey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
FirebaseApp.initializeApp(options);
}
catch(Exception e){
e.printStackTrace();
}
}
}
build.gradle
implementation 'com.google.firebase:firebase-admin:6.8.1'
-> 이것만 추가해 주면 된다.
(전체코드)
plugins {
id 'org.springframework.boot' version '2.3.5.RELEASE'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
}
group = 'DSC4'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
//implementation 'android.arch.persistence.room:runtime:1.1.1'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
implementation 'com.google.firebase:firebase-admin:6.8.1'
//annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
}
test {
useJUnitPlatform()
}
[ 실행 방법 ]
application을 선택한 후 재생버튼 클릭
인터넷 창을 켜서 다음을 입력한다.
http://localhost:8080/getMemberDetail?id=문서아이디
※ 나의 경우 9070 port를 이용했다. ( http://localhost:9070/getMemberDetail?id=FMgoGDQHyNQ7IfGycZ0h )
id로 FMgoGDQHyNQ7IfGycZ0h을 줬기 때문에
문서id가 FMgoGDQHyNQ7IfGycZ0h인 것의 내용이 출력되는 것이다.
+) 참고
localhost 8080을 이용하고 있어서 9070으로 변경했다.
application.properties
server.port=9070
+) 참고2
serviceAccountKey.json 을 resource 폴더에 저장해서 관리했다.
하지만 이대로 깃허브에 올리면 난리가 나므로 .gitignore에 추가했다.
.gitignore
serviceAccountKey.json
'데이터베이스' 카테고리의 다른 글
[ 용어 ] '행, 열, 필드, 레코드, 튜플, 속성, 필드' 도대체 뭐가 뭐야? (0) | 2021.11.27 |
---|---|
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. (0) | 2020.12.26 |
[Spring boot] mysql 연결 (실패..) (0) | 2020.12.26 |
[ php - MySQL ] php와 MySQL 연결하기 (1) | 2020.12.04 |
[ php ] <?php phpinfo(); ?> 그대로 보일 때 (1) | 2020.12.03 |