Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

JAVA Developer Training

22. CourseDB 본문

트레이닝

22. CourseDB

Romenest 2021. 9. 2. 14:56
package com.example.model;

import java.util.ArrayList;
import java.util.List;

import com.example.config.Setting;
import com.example.entity.Course;
import com.example.entity.Professor;
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.Projections;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.InsertOneResult;

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

public class CourseDB {
    private MongoDatabase db = null;
    private MongoCollection<Document> courseCollection = null;
    private MongoCollection<Document> seqCollection = null;

    private static CourseDB courseDB = new CourseDB();

    public CourseDB() {
        MongoClient client = MongoClients.create(Setting.URL);
        this.db = client.getDatabase(Setting.DBNAME);
        this.courseCollection = db.getCollection(Setting.COURSE_COLLECTION);
        this.seqCollection = db.getCollection(Setting.SEQ_COURSE_COLLECTION);
    }

    public static CourseDB getInstance() {
        return courseDB;
    }

    // // 과목 추가
    public boolean insertCourse(Course course) {

        Bson queryBson = Filters.eq("_id", "SEQ_COURSE_NO");
        Bson updateBson = Updates.inc("seq", 1);

        Document doc = seqCollection.findOneAndUpdate(queryBson, updateBson);
		//과목번호를 자동으로 할당시키기 위한 seq사용
        
        
        long corid = doc.getLong("seq");

        Document doc1 = new Document();
        doc1.append("_id", corid);
        doc1.append("name", course.getCorname());
        doc1.append("point", course.getCorpoint());
        doc1.append("professor", course.getProfessor().getProid());	//교수자에서 아이디와 이름을 가져온다
        doc1.append("professorname", course.getProfessor().getProname());
        doc1.append("cordate", course.getCordate());

        long ret = courseCollection.insertOne(doc1).getInsertedId().asInt64().getValue();
															// long 타입 = asInt64 이후 getValue
        if (ret == corid) {
            return true; // 리턴타입이 오류날경우 41열의
        }			     // public boolean insertCourse(Course course) 확인 해당값과 boolean의 위치의 타입이 동일해야한다

        return false;
    }
    
    //전체 과목 조회 (과목 코드 , 과목 이름, 학점, "교수이름" , 날짜)
    public List<Course> selectCourse() throws Exception {

        MongoCursor<Document> cursor = this.courseCollection.find().sort(Filters.eq("_id", 1)).iterator();

        List<Course> list = new ArrayList<>();
        while (cursor.hasNext()) {

            Document doc = cursor.next();

            //course에서는 교수번호 외의 교수자의 정보를 받을수 없어 다른 DB를 호출해 받는다
            Professor professor = ProfessorDB.getInstance().selectProfessorOne(doc.getLong("professor"));
            //교수번호를 이용해 교수를 찾는 기능
            
            Course course = new Course();

            course.setCorcode(doc.getLong("_id"));
            course.setCorname(doc.getString("name"));
            course.setCorpoint(doc.getInteger("point"));
            course.setCordate(doc.getDate("cordate"));
            //이후 course에 교수자정보를 모두 넣는다
            course.setProfessor(professor);

            list.add(course);

        }
        return list;
    }
    
    // 교수 번호별 과목 조회
   public List<Course> selectCourseProfessor(long no) {
        Bson filter = Filters.eq("professor", no);
        MongoCursor<Document> cursor = courseCollection.find(filter).cursor();

        List<Course> list = new ArrayList<>();
        if (cursor.hasNext()) {
            Document doc = cursor.next();

            // course에서는 교수번호 외의 교수자의 정보를 받을수 없어 다른 DB를 호출해 받는다
            Professor professor = ProfessorDB.getInstance().selectProfessorOne(doc.getLong("professor"));
            // 교수번호를 이용해 교수를 찾는 기능

            Course course = new Course();

            course.setCorcode(doc.getLong("_id"));
            course.setCorname(doc.getString("name"));
            course.setCorpoint(doc.getInteger("point"));
            course.setCordate(doc.getDate("cordate"));
            // 이후 course에 교수자정보를 모두 넣는다
            course.setProfessor(professor);

            list.add(course);
        }

        return list;
    }

 

매번 리스트를 만들어 반복하여 작성하기에는 코드가 더러워 보일 수 있어 따로 떼어내서 만들었다

 List<Course> list = new ArrayList<>();
        while (cursor.hasNext()) {

            Document doc = cursor.next();

            // course에서는 교수번호 외의 교수자의 정보를 받을수 없어 다른 DB를 호출해 받는다
            Professor professor = ProfessorDB.getInstance().selectProfessorOne(doc.getLong("professor"));
            // 교수번호를 이용해 교수를 찾는 기능

            Course course = new Course();

            course.setCorcode(doc.getLong("_id"));
            course.setCorname(doc.getString("name"));
            course.setCorpoint(doc.getInteger("point"));
            course.setCordate(doc.getDate("cordate"));
            // 이후 course에 교수자정보를 모두 넣는다
            course.setProfessor(professor);

            list.add(course);

        }
        return list;

사용법은 기존 코드에서 return으로 주면 된다.

// 학점 n이 전달되면 n점 이하 인것만 조회
    public List<Course> selectCoursePoint(int point) {
        Bson query = Filters.lte("point", point);
        // eq 같음, lte 이하 , lt, 미만 , get 이상, gt 초과
        MongoCursor<Document> cursor = this.courseCollection.find(query).cursor();
        return cursorToList(cursor);
    }

한줄추가로 깔끔한 기능 완성

기존의 List를 사용하는 메소드들은 다 사용할 수 있다고 생각하면 된다.

 

App.java에서 실행

 

public class App {
    public static void main(String[] args) throws Exception {

        //교수 이름까지 호출
        List<Course> list = CourseDB.getInstance().selectCourse();
        
        for (Course course : list) {
            System.out.println(course.getCorcode());
            System.out.println(course.getCorname());
            System.out.println(course.getCorpoint());
            System.out.println(course.getCordate());

            System.out.println("=================");
            System.out.println(course.getProfessor().getProname());
        }
    }

}