java

국비 코딩 풀스택 수업 38일차 lombok, static, 서버관리 폴더따로, entity, ArrayList

비루블 2022. 8. 18. 09:10

요약정리

https://velog.io/@hoyun7443/Service%EC%99%80-Impl%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4-%EC%97%AD%ED%95%A0
service와 impl 설명 역할

App.java -> StudentService(interface 인터페이스) -> StudentServiceImpl(여기서 메서드 기입) -> App.java

간단히 설명하자면 service와 impl은 (app.java와 student를 같이 쓸때 약속약속약속 만들기임)

 

config> MongoConfig.java로 서버 접속 따로 관리

 

static 개념 다시 알아보기(미완료)

 

동적할당 ArrayList (배열을 정해주는 것보다 속도가 느려짐)

 

combine으로 병합후 updateOne에 한번에 넣어줌

 

수정할때 데이터 병합하여 한번에 넣어줌
Bson arg4 = Updates.combine(arg1, arg2, arg3);

UpdateResult result = this.collection.updateOne(arg0, arg4);

 

spring 가면(프레임 워크 가면) 오늘 짜는거 거의 안짬(impl)
service는 우리가 직접해야함. 여기가 가장 중요.

 

오전일과
exam_static > Ex01.java
lombok으로 getter/ setter 생략

 

static이란 클래스 배울 것임.

 

 

App.java
static 설명

 

//08_17am
// 클래스명 객체명 = new 생성자();
// static은 객체 생성 생략
// Ex01 obj = new Ex01();
// static는 객체가 생성 되어있는 것임
// 그래서 클래스명.메소드(); 바로 하는 것임
// 몽고디비에서도 create라는 static을 썻음.
// 쓸때마다 객체가 생성 되기때문에 넣었음.
// 데이터베이스이기 때문 Integer는 한번만 쓰라는 의미(객체를 만들지마라)
// 디자인 패턴이라는 것임.(효율적인 설계를 위해서)(리팩토링)

int ret = Ex01.getNum2();
System.out.println(ret);


exam_static > Ex02.java

서버 접속할때 config로 따로 관리 + 한번만 접속하게끔 만듬
config> MongoConfig.java

package com.example.config;

import org.bson.Document;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoConfig {

    // 1. 객체 생성
    private static MongoConfig obj =  new MongoConfig();
    private final String url = "mongodb://id203:pw203@1.234.5.158:37017/db203";

    // 2. 객체 리턴
    public static MongoConfig create() {
        return obj;
    }

    // 3. 메소드
    public MongoCollection<Document> getConnection(
                        String collectionName ) {
        MongoClient client = MongoClients.create(this.url);
        if(client != null) {
            MongoDatabase db = client.getDatabase("db203");
            return db.getCollection(collectionName);
        }
        return null;
    }
}

 

 

 

mongodb> BooksDB.java
public BooksDb
아래부분 몽고디비컨피그에서 끌어오도록 만듬

this.collection = MongoConfig.create().getConnection("books");
package com.example.mongodb;

import java.util.Date;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.example.config.MongoConfig;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.InsertOneResult;
import com.mongodb.client.result.UpdateResult;

public class BooksDB {

    // 상수
    private final String url = "mongodb://id203:pw203@1.234.5.158:37017/db203";

    // 변수
    private MongoCollection<Document> collection = null;

    // DB에 연결하기
    public BooksDB() {
        // MongoClient client = MongoClients.create(this.url);
        // if(client != null){
        //     // System.out.println("DB접속성공");
        //     MongoDatabase db = client.getDatabase("db203");

        //     this.collection = db.getCollection("books");
        //     // System.out.println(collection.toString());

        //     // MongoCursor<String> cols =  db.listCollectionNames().iterator();

        //     // while(cols.hasNext()){ // 다음 것이 있으면 true, 없으면 fale
        //     //     // 다음 것을 가져오면서 출력하기
        //     //     System.out.println(cols.next());
        //     // }
        // }

        this.collection = MongoConfig.create().getConnection("books");
    }

    // 메소드 : 추가하기
    public int insert() { // 저장 하기
        try{
            Document doc = new Document();
            doc.append("_id", 22);
            doc.append("title", "제목");
            doc.append("author", "저자");
            doc.append("price", 1234);
            doc.append("regdate", new Date());
            InsertOneResult result = this.collection.insertOne(doc);
            System.out.println(result.getInsertedId());
            return 1;
        }
        catch(Exception e){
            e.printStackTrace(); //오류표시됨
            return 0;
        }
    }

    public void select() { // cursor()랑 iterator() 똑같은 말임. 리턴값도 똑같
        // iterator 반복자(포함된 개수 모름)
        // 가지고 온 것에서 한개라도 빼면 잘못된 것.
        // find()에 쿼리값 넣어서 가져오는 것이 출력에 용이
        MongoCursor<Document> list = this.collection.find().iterator();

        while(list.hasNext()){ // 가지고 올 다음 데이터가 있나요? 없으면 ㅌㅌ하세요.
            Document doc = list.next(); // 다음 것 가져오기

            // System.out.println(doc.toString()); // 전부 가져오기
            System.out.println(doc.getInteger("_id")); // 원하는 것만 들고오기
            System.out.println(doc.getString("title"));
        }
    }


    public int delete( int code ) { // 삭제 하기
        try{
            Bson query = Filters.eq("_id", code);
            DeleteResult result = this.collection.deleteOne(query);
            System.out.println(result);
            if(result.getDeletedCount() == 1L){
                return 1;
            }
            return 0;
        }
        catch(Exception e){
            e.printStackTrace();
            return -1;
        }
    }

    // 수정하기(조건정보, 제목, 저자, 가격)
    public int update ( int code, String title, String author, int price){
        try{
            // 수정할 조건 정보
            Bson arg0 = Filters.eq("_id", code);

            // 수정할 항목들
            Bson arg1 = Updates.set("title", title);
            Bson arg2 = Updates.set("author", author);
            Bson arg3 = Updates.set("price", price);

            Bson arg4 = Updates.combine(arg1, arg2, arg3);

            UpdateResult result = this.collection.updateOne(arg0, arg4);
            if(result.getModifiedCount() == 1L){
                return 1;
            }
            return 0;
        }
        catch(Exception e){
            e.printStackTrace();
            return -1;
        }
    }
}


mongodb> BooksDB.java
delete에 try형식
리턴타입
.getDeletedCount

update에서 코드를 주고 수정항목 3개를 한번에 넣는 방법을 배움
combine(arg1, arg2, arg3, arg4)

app.java

service> StudentService
interface
app.java와 student를 같이 쓸때 약속약속약속 만들기임
여기 중요중요중요중요중요중요중요중요
중요중요중요중요중요중요중요중요
중요중요중요중요중요중요중요중요

package com.example.service;

import com.example.exam_cls.Student;

// 변수생성x 안됨, 메소드를 구현x 안됨
// interface 설계부분
// 유료 프레임워크를 사면 쫙 나와있음.
// 규칙, 약속
// 함수 명을 정의만 할 수 있음. 구현 불가능
public interface StudentService {
    // // 아래 것들 불가능
    // private int num = 0;
    // public void print() {
    // }

    // 추상화 정의만 구현불가

    // app.java와 student를 같이 쓸때 약속 만들기임
    // db에서는 주는 것만 조회하면 안됨
    // 학생의 정보가 오면 추가한 후에
    public int insertStudent( Student obj ); // 반환타입 int
        // obj로 받고 나가는 것 return값은 int임. obj는 넣는 것만 하는 것, 넣는 다면 int로 반환.

    // 삭제
    public int deleteStudent (int no);

    // 수정
    public int UpdateStudent( Student obj );

    // 조회
    public Student[] selectStudent();
    // 학생 정보가 배열로 (목록으로) 오면 됨.
}



service> StudentServiceImpl

오버라이드 만들고(위 사진)
app.java로 이동
obj.을 보면 수동으로 추가한 print가 없음.

 



https://velog.io/@hoyun7443/Service%EC%99%80-Impl%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4-%EC%97%AD%ED%95%A0
service와 impl 설명 역할


오후일과

동적할당 ArrayList


service impl
        // 배열은 전체 개수를 알아야 됨.
        // 배열은 정적할당이기 때문
        Student[] list1 = new Student[10];

        // 동적할당 -> 개수를 정하지 않음,
        // 데이터가 추가되면 개수가 증가 또는 감소 됨.
        ArrayList<Student> list2 = new ArrayList<>();

service 
    // 조회
    public ArrayList<Student> selectStudent();
    // 학생 정보가 배열로 (목록으로) 오면 됨.



spring 가면(프레임 워크 가면) 오늘 짜는거 거의 안짬
service는 우리가 직접해야함. 여기가 가장 중요.




db.vuerd.json


erd 설계
erd 설계 했던걸 
모델?로 만드는 것은 entity라고 함.

entity 설계 5가지 함. (classroom, student, professor, enrollcouse, course)
list부분 다시 확인 해봐야할듯.


app.java

        // 학생 조회
        StudentService obj = new StudentServiceImpl();
        System.out.println(obj.selectListStudent(0));



        // // 학생 삭제 (완료)
        // StudentService obj = new StudentServiceImpl();
        // Student student = new Student ();
        // student.setNo(1L);
        // obj.deleteStudent(student);



        // // 학생 업데이트 정보 수정(완료)
        // StudentService obj = new StudentServiceImpl();
        // Student student = new Student ();
        // student.setNo(3L);
        // student.setName("헝길동");
        // student.setPhone("111-111-111");
        // obj.updateStudent(student);



        // // 학생 1명 조회(완료)
        // StudentService obj = new StudentServiceImpl();
        // Student student = new Student();
        // student.setNo(5L);
        // System.out.println(obj.selectOneStudent(student));

        // // 학생 만들기(완료)
        // StudentService obj = new StudentServiceImpl();
        // Student student = new Student();
        // student.setNo(5L);
        // student.setName("홍길동");
        // student.setPhone("000-000-000");
        // student.setRegdate(new Date());
        // obj.insertStudent(student);

        // System.out.println(obj.selectOneStudent(Student));


//=======================================================================================================

        // // 08_17am
        // // 인터페이스 객체명 = new 실제구현클래스();
        // StudentService obj = new StudentServiceImpl();

        // Student student = new Student ("name", 1, 3, 1, 1, 1);
        // obj.insertStudent(student);
        // // obj.을 보면 print가 없음

        // // 업데이트 안됨@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 됫음
        // // // 08_17am 업데이트
        // // // 인터페이스 객체명 = new 실제구현클래스();
        // StudentService obj = new StudentServiceImpl();

        // Student student = new Student ("name123", 1, 3, 1111, 111, 111);
        // obj.UpdateStudent(student);


        // // 08_17am
        // BooksDB obj = new BooksDB();
        // obj.update(20, "qweqw", "3213", 11111);

        // // 08_17am
        // BooksDB obj = new BooksDB();
        // obj.delete(22);

        // // 08_17am
        // // static Ex02
        // Ex02 obj = Ex02.create();
        // obj.print();

        // //08_17am
        // // 클래스명 객체명 = new 생성자();
        // // static은 객체 생성 생략
        // // Ex01 obj = new Ex01();
        // // static는 객체가 생성 되어있는 것임
        // // 그래서 클래스명.메소드(); 바로 하는 것임
        // // 몽고디비에서도 create라는 static을 썻음.
        // // 쓸때마다 객체가 생성 되기때문에 넣었음.
        // // 데이터베이스이기 때문 Integer는 한번만 쓰라는 의미(객체를 만들지마라)
        // // 디자인 패턴이라는 것임.(효율적인 설계를 위해서)(리팩토링)
        
        // int ret = Ex01.getNum2();
        // System.out.println(ret);