데이터베이스2020. 12. 26. 20:10
728x90

MySQL 을 이용하려다가

결국 성공하지 못하고 파이어베이스의 Firestore로 갈아타려고 했다.

 

하지만 에러가 발생했다.

firestore Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

 

MySQL 관련된 내용을 다 지웠는데 왜 뜨지? 했는데

다시 찾아보니

 

build.gradle 에 jpa, jdbc 가 남아있었다..!

 

완전히 제거한 후 돌리니 해결완료 :)

 

 

 

 

[ 요약 ]

 

* MySQL 등

 

application.properties 에 다음을 추가한다. (확실 X)

spring.datasource.url=jdbc:mysql://localhost:3306/데이터베이스명?autoReconnect=true
spring.datasource.username=아이디
spring.datasource.password=비밀번호
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 

 

* MySQL 이용하다가 취소한 경우

전체 파일에서 jpa, jdbc, mySQL 관련 항목을 지운다

특히 build.gradle 에서!

반응형
Posted by mminky
데이터베이스2020. 12. 26. 19:55
728x90

* 프레임워크 : Spring Boot

* 프로젝트 : Gradle

* 데이터베이스 : firebase의 firestore

 

 

[결과]

 

 

[ Firestore ]

 

우선 파이어스토어에 다음과 같이 데이터를 넣는다.

(문서IDFMgoGDQHyNQ7IfGycZ0h 이런 식으로 설정 할 필요는 없습니다!

제가 잘 모르고 자동완성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을 줬기 때문에

문서idFMgoGDQHyNQ7IfGycZ0h인 것의 내용이 출력되는 것이다.

 

 


 

 

+) 참고

localhost 8080을 이용하고 있어서 9070으로 변경했다.

 

application.properties

server.port=9070

 

 

+) 참고2

serviceAccountKey.json 을 resource 폴더에 저장해서 관리했다.

하지만 이대로 깃허브에 올리면 난리가 나므로 .gitignore에 추가했다.

 

.gitignore

serviceAccountKey.json

 

 

 

반응형
Posted by mminky
데이터베이스2020. 12. 26. 12:32
728x90

spring boot와 mySQL 연결을 시도 했지만

데이터베이스에 관한 지식이 별로 없어서 성공하지는 못했습니다ㅠㅠ

 

* myBatis 등 mySQL과 웹을 연결하는 프레임워크를 공부할 것

 

더 공부한 뒤 참조하기 위해 글을 남깁니다.

 


* 언어 : spring boot

* 프로젝트 : gradle

* 데이터베이스 : mySQL


 

.domain / Member.java

package DSC4.cafein.domain;

import javax.persistence.*;

@Entity
@Table(name="member")
public class Member {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private String email;
    private String username;
    private String password;

    public Member() {

    }


    public Member(String username,String password){
        this.email = username;
        this.password = password;
    }

    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 getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

 

 

.repository / MemberRepository.java

package DSC4.cafein.repository;

import DSC4.cafein.domain.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface MemberRepository extends JpaRepository<Member,String> {
    Member findByUsernameAndPassword(String username,String password);
}
//public class MemberRepository {
//}

 

 

.service / MemberService.java

package DSC4.cafein.service;

import DSC4.cafein.domain.Member;
import DSC4.cafein.repository.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MemberService {

    @Autowired
    private MemberRepository repo;

    public Member login(String username, String password){
        Member member = repo.findByUsernameAndPassword(username,password);
        return member;
    }
}

 

 

build.gradle

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'
	runtimeOnly 'mysql:mysql-connector-java'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	//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'
	compile('org.springframework.boot:spring-boot-starter-data-jpa')
	compile('org.springframework.boot:spring-boot-starter-jdbc')
	compile('mysql:mysql-connector-java')

}

test {
	useJUnitPlatform()
}

-> 사실 여기는 firebase와 mysql코드가 섞여있다.

 

(아래의 코드는 파이어베이스 코드이니 무시 가능)

implementation 'com.google.firebase:firebase-admin:6.8.1'

 

 

반응형
Posted by mminky
728x90

혹시 다음에 하게 될 분들을 위해
간단하게 후기를 남깁니다

[ 장점 ]
* 자유롭다
밖에서 근무하다보니 아무도 나에게 터치를 안한다
물론 환경공단과 관리사무소에서 출 퇴근은 확인한다

* 주휴수당...! 유급 휴가...! (최고다 ◡̈ )

* 큰 아파트가 걸리면 운동을 할 수 있다!
-> 나의 경우 관리지역에 넓은 아파트가 하나 있었는데 동마다 거리가 있어 하루에 10,000보 이상씩 걸었다

* 내 집 근처에서 일할 수 있다
-> 나는 추가합격이라 좀 떨어진 곳에서 근무를 했다
하지만 대부분 근처에 배정해준다
교통비가 들지 않는게 장점!
본인 아파트에서 근무하는 분도 봤다!


[ 단점 ]
* 생각보다 한국환경공단-아파트 간의 의견 충돌이 있다
-> 이런건 일반쓰레기에요~ 하고 알려드리며 버리는 종량제 봉투가 있는데 개수를 조사해야한다.
하지만 아파트에 따라 신경끄라고 하시면서 화내는
곳도 있다. (물론 협조를 매우 잘 해주는 곳도 있다.)

-> 관리사무소에서 30분 휴식, 물, 화장실 등을 이용하라고 했다. 하지만 관리사무소가 쉬는곳이냐며 누가 그런소리 하냐며 안된다는 곳도 있었다.. (아예 들어와서 쉬라는 곳도 있었지만)

* 너무 다양한 사람이 많아서 멘탈이 세야한다
->(너무 좋은 사람도 있지만.. 쓰레기가지고 왜이래? 하면서 화를 내는 사람도 꽤 있다)

* 춥다.. 냄새난다.. 야외근무 힘들다..
-> 나는 겨울쯤에 저녁에 일을 했다..
햇빛도 없고 쓰레기장에서는 냄새가 나고..
(여름엔 아마 벌레까지 있지 않을까..?!)
마냥 쉬운 일은 아니었던 것 같다..
하지만 주휴수당에 휴가까지 주는 걸 보면 버틸만하다!
(물론 세금도 떼간다)



이 일을 한 것에 대해 후회는 하지 않는다.
그 덕에 밖에서 전단지를 돌리는 분이나 야외근무 하는 분,
쓰레기장에서 근무하는 분들의 고충을 알 것 같다..

제일 큰 깨닳음은 사람 대하는 법을 배웠다
내가 대우를 받고싶으면 상대를 그렇게 대우하라고 했다
그 말을 뼈저리게 느낀 두 달이었다

쓰레기장에서 분리수거 한다고 나를 깨끗하지 않다는 듯이 본 사람도 있었고
외부인이라 달갑지 않아하는 분도 있었고
나는 분리배출 무조건 잘하고 있으니깐 건들지 마라는
분도 봤다

반면 고생하시네요~ 라는 따뜻한 말 한마디를 건네는 사람도 있었고
춥다며 따뜻한 두유를 주신 분도 있었고
나보다 더 나서서 분리배출 하라고 해주시는 분도 계셨다

앞으로 후자의 사람이 되기 위해 노력해야겠다

- 끝 -


+)
이 일이 끝날때 쯤 보니 장갑이 다 까질 정도로 라벨과 박스테이프를 열심히 뗐던 것 같다...
이 활동을 통해 환경이 조금은 더 나아졌으면 좋겠다는게 내 바램이다 ◡̈

 

 

※ 제 글이 도움이 되었다면 공감 부탁드려요 ◡̈

반응형
Posted by mminky
728x90

투명페트병은 라벨(비닐)을 떼서 버려야 하는데요!
자원관리도우미가 안내 및 시범을 해야합니다!

오늘은 제가 하면서 정말 힘들었던 친구들과
아주 좋았던 친구들을 소개하려고 합니다 :)

😀칭찬해😀
* 삼다수
라벨 분리선 이라고 접착제가 없는 부분이 있습니다!
그래서 뜯기가 훨씬 수월하고
전체적으로 접착제가 약해서 진짜 제일 좋아하는 페트병이에요!!
앞으로 삼다수만 먹어야지🧡


* 빅토리아
그냥 한 번 돌리고 위로 쭉 빼주면
라벨이 그대로 분리되어서 좋았어요 ◡̈




😔힘들어..😔
* 탄산음료
왜인지는 모르겠지만 다들 접착제가 너무 세요ㅠ
세게 붙여야 탄산이 안나가는건지ㅠ

환경을 위해 개선이 되면 좋을거같네요!

 

(어디를 뜯어야하죠ㅠ)

 



+) 환경공단에서 또 소포를 받았습니다!
새 전단지와
핫팩 그리고 귀마개를 받았습니다 ◡̈
잘 쓰겠습니다!👍


수령한 전단지 입니다!

 



 

※ 제 글이 도움이 되었다면 공감 부탁드려요 ◡̈

반응형
Posted by mminky
데이터베이스2020. 12. 4. 03:05
728x90

(MySQL에 이미 데이터를 넣어놓은 상태입니다.)  참고

* DB명: cafein

* table명: member

 

 

[ php\ php.ini ]

php 디렉토리 내의 php.ini 파일을 수정합니다.

 

;extension=mysqli 이렇게 되어있을텐데

주석 역할을 하는 ; 을 지우고 저장합니다.

extension=mysqli

 

 

아파치 (apache) 서버 재시작 합니다.

cmd창 (관리자 모드)

 

httpd.exe -k restart

 

(소문자 k 입니다)

 

 

 

[ Apache24\htdocs\ 이름.php ]

확인을 위해서 apache24 디렉토리 밑에 htdocs 디렉토리에

이름.php 파일을 생성합니다. (저는 test.php 로 했습니다.)

 

 

.php 파일을 만드는 방법은

더보기

-------------------------(더보기)-------------------------

우선 메모장으로 코드를 입력한 후 저장합니다.

 

그리고 파일탐색기에서

'보기' > '파일확장명'체크 를 합니다.

 

원하는 파일을 선택한 후 이름바꾸기(혹은 F2)를 눌러 확장자를 변경합니다.

 

.txt -> .php

 

-------------------------(더보기)-------------------------

 

 

 

test.php

<?php
$mysql_hostname = 'localhost';
$mysql_username = 'root'; //계정명
$mysql_password = 'password'; //계정 비밀번호
$mysql_database = 'cafein'; //db명
$mysql_table = 'member'; //table명
$mysql_col1 = 'num'; //col1 명
$mysql_col2 = 'email'; //col2 명
$mysql_col3 = 'pw'; //col 3명
//$mysql_port = '3306';
$sql = "SELECT * FROM ".$mysql_table;
$connect = mysqli_connect($mysql_hostname, $mysql_username, $mysql_password, $mysql_database);

mysqli_select_db($connect, $mysql_database) or die('DB 선택 실패');
$result = mysqli_query($connect, $sql);
while($info=mysqli_fetch_array($result)){
    echo $info[$mysql_col1]." | ";
    echo $info[$mysql_col2]." | ";
    echo $info[$mysql_col3]."<br/>\n";
}
mysqli_close($connect);
?>

 

각자에 맞게 위에 변수의 값을 변경해서 이용하시면 될 것 같습니다 :)

 

 

[ 결과 ]

 

 

[ 실제 table ]

 

 

반응형
Posted by mminky
데이터베이스2020. 12. 3. 22:36
728x90

[ 에러 ]

Apache24\htdocs 의 min.php에 다음과 같이 입력했다.

 

<?php phpinfo(); ?>

 

원래라면 127.0.0.1/min.php를 했을 때 phpinfo화면이 나타나야 하는데

텍스트 그대로 나타났다.

 

Apache24\conf 의 httpd.config 파일에 다음과 같이 적었더니 작동이 되지 않았다.

AddType application\x-httpd-php .php .html
AddHandler application\x-httpd-php .php .html

 

 

 

※ 최신버전인 php8_module은 에러가 발생하는 것 같아서

일부러 php7을 다운받아서 php7_module을 이용했다.

 

 

 

[ 해결책 ]

이전의 코드 대신 다음의 코드를 입력하였다.

 

#PHP
LoadModule php7_module "C:\Users\min\php\php7apache2_4.dll"
AddType application/x-httpd-php .php .htm .html .inc
AddType application/x-httpd-php-source .phps


#configure the path to php.ini
PHPIniDir "C:\Users\min\php"

 

참고로 이 코드는 Apache24\conf httpd.config 파일의 마지막에 입력해야 한다.

 

그리고 Apache를 재시작한다.

Cmd창 (관리자 권한)

httpd.exe -k restart

 

그리고 127.0.0.1/이름.php 에 접속한다.

 

진짜 이 화면보고 눈물날뻔했다..〒▽〒

여러분들도 꼭 성공하길 바랍니다!

 

 

 

+) 혹시 안된다면

php 디렉토리의 php.ini 파일을 열어서 다음을 On으로 수정해준다.

(php를 여는 짧은 태그를 허용해준다는 의미이다.)

 

short_open_tag = On

반응형
Posted by mminky
데이터베이스2020. 12. 3. 21:59
728x90

[ 에러 ]

apache를 restart 하기 위해서

cmd창을 관리자 권한으로 실행한 후 명령어를 입력하였더니

다음과 같은 에러가 발생했습니다.

 

C:\WINDOWS\system32>httpd.exe -k restart
AH00558: httpd.exe: Could not reliably determine the server's fully qualified domain name, using fe80::b5f6:60c5:4cf:3015. Set the 'ServerName' directive globally to suppress this message

 

 

[ 해결책 ]

우선 apache24 \ conf 디렉토리의 httpd.conf 파일을 메모장으로 엽니다.

ctrl + F 로 ServerName 을 검색합니다.

 

주석(#)을 지우고 localhost 혹은 127.0.0.1 을 입력합니다.

 

ServerName localhost

 

 

 

그리고 apache를 다시 restart합니다.

 

httpd.exe -k restart

 

에러없이 실행되는 것을 알 수 있습니다.

 

 

※ 제 글이 도움이 되었다면 공감 부탁드려요 ◡̈

반응형
Posted by mminky