JAVA #12 - Item

김형우·2022년 2월 25일
0

JAVA

목록 보기
12/12

ItemImple.java

1. 물품추가 - 시퀀스사용

  1. DB연동
    : 시퀀스 컬렉션은 seqCollection
    : item2 컬렉션은 collection
private final String url = "mongodb://id201:pw201@1.234.5.158:37017/db201";
private MongoCollection<Document> collection = null; // item2
private MongoCollection<Document> seqCollection = null; // sequence

    // DB접속
    public ItemDBImpl() {
        MongoClient client = MongoClients.create(this.url);
        MongoDatabase db = client.getDatabase("db201");
        this.seqCollection
        : item2 컬렉션은= db.getCollection("sequence");
        this.collection = db.getCollection("item2");
    }
  1. 시퀀스를 사용한 item 추가
// 추가
@Override
public int insertItem(Item item) {
    try {
        Bson filter = Filters.eq("_id", "SEQ_ITEM2_NO");
        Bson update = Updates.inc("seq", 1);
        // Bson bson2 = Filters.eq("SEQ_ITEM2_NO", item.getId() + 1);
        Document document = this.seqCollection.findOneAndUpdate(filter, update);
        long seq = document.getLong("seq");
        System.out.println(seq);

        // Item item2 = new Item();
        Document document1 = new Document();
        document1.append("_id", seq);
        document1.append("name", item.getName());
        document1.append("price", item.getPrice());
        document1.append("quantity", item.getQuantity());
        System.out.println("document1 ===> " + document1);
        InsertOneResult result = this.collection.insertOne(document1);
        System.out.println("result ===> " + result);

        if (result.getInsertedId().asInt64().getValue() == seq) {
            return 1; // 성공
        }
        return 0; // 실패

    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

2. 물품삭제 - Throw Exception

  1. 예외(오류)처리를 App으로 넘김
    : throws Exception
    : 오류를 잡는 주체가 DBImpl에서 App으로 바뀐것
    1-1. 예외처리
    : db가 꺼지는 등 물리적 오류를 잡아줌
// 삭제
@Override
public int deleteItem(long code) throws Exception {

    // throws Exception 추가함
    // db가 꺼지는 등 물리적 오류를 잡아줌
    // 오류 처리 안할래, 니가해
    // 오류를 잡는 주체가 DBImpl에서 App으로 바뀐것

    // Filters filt = new Filters();
    // Bson filter = filt.eq("_id", code)
    // 위와 같은 형태로 가야하지만 Filters가 static이라 아래처럼 사용하면 된다.
    // 즉 객체생성이 불필요함
    Bson filter = Filters.eq("_id", code);
    DeleteResult result = this.collection.deleteOne(filter);
    System.out.println("result ===> " + result);
    if (result.getDeletedCount() == 1L) {
        return 1;
    }
    return 0;

}

3. 수정

  1. Item class의 id 부분에 _id를 임시로 넣어서 사용
// 수정
@Override
public int updateItem(Item item) {
    try {
        Bson filter = Filters.eq("_id", item.getId());
        Bson name = Updates.set("name", item.getName());
        Bson price = Updates.set("price", item.getPrice());
        Bson quantity = Updates.set("quantity", item.getQuantity());
        Bson update = Updates.combine(name, price, quantity);

        UpdateResult result = this.collection.updateOne(filter, update);
        System.out.println("result ===> " + result);
        if (result.getModifiedCount() == 1) {
            return 1;
        }
        return 0;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

4. 한개 조회

4-1. Map 사용

  1. Object타입은 모든 타입이 가능
  2. Map 과 Item(class)의 차이
    2-1. Map
    : class 파일이 필요없기 때문에 원하는 모양으로 데이터를 가공할 수 있다.
    : key값(변수)을 원하는대로 정할수 있다.
    : 원하는 양만큼 임의의 key를 생성할수 있다.
    : 데이터 처리가 자유롭고, 유연하다.
    : 단점 - 협업에 불리하다.
    2-2. Class(Item등)
    : class 파일에서 정해진 형태로 데이터를 처리하야한다.
    : 협업에 유리하다.
    : 테이터의 총량을 미리 정함으로써 개발자와 사용자의 이해가 쉽다.
    : 단점 - 유연성이 부족하다.
  3. find();
    : FindIterable<Document> document = this.collection.find(filter);
    : filter의 형식은 Bson
    : 위의 코드가 수행되는 시점에 document에 이미 데이터 (조건에따라)n개가 들어있다.
    : 압축의 개념
    : 안에 있는데 이터를 꺼내는데 for문(반복문)이 필요하다.
// 1개조회 Map
@Override
public Map<String, Object> selectOneMapItem(long code) {
    try {
        Bson filter = Filters.eq("_id", code);
        Map<String, Object> map = new HashMap<>();
        FindIterable<Document> document = this.collection.find(filter);        
        for (Document tmp : document) {
            // map키(변수)를 마음대로 해서 추가함.
            map.put("ID", tmp.getLong("_id"));
            map.put("NAME", tmp.getString("name"));
            map.put("PRICE", tmp.getLong("price"));
            map.put("QUANTITY", tmp.getLong("quantity"));
        }
        return map;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

4-2. class(Item) 사용

// 1개조회 #1 - Item안에 넣어서 Item을 던짐
@Override
public Item selectOneItem(long code) {
    try {
        Bson filter = Filters.eq("_id", code);
        FindIterable<Document> document = this.collection.find(filter);
        Item item = new Item();
        for (Document tmp : document) {
            item.setId(tmp.getLong("_id"));
            item.setName(tmp.getString("name"));
            item.setPrice(tmp.getLong("price"));
            item.setQuantity(tmp.getLong("quantity"));
        }
        return item; 
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

// 1개조회 #2 - 바로리턴
@Override
public Item selectOneItem(long code) {
    try {
        Bson filter = Filters.eq("_id", code);
        FindIterable<Document> document = this.collection.find(filter);        
        for (Document tmp : document) {
        	return new Item(
        		tmp.getLong("_id"),
        		tmp.getString("name"),
        		tmp.getLong("price"),
        		tmp.getLong("quantity")
            );
        }
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

5. 전체 조회 - name 제외

  1. 전체를 조회 할거기 때문에 조건인 find();는 비워둔다.
  2. 정렬을 하기위해 sort(filter); 사용
    : 조건은 "_id"를 오름차순으로
    : Bson filter = Filters.eq("_id", 1);
  3. "name"은 빼고 불러오기위해 projection(projectiion);사용
    : 변수 projection은 Bson 타입
    : Bson projection = Projections.exclude("name");
    : 제외(exclude), 추가(include)
  4. 생성자를 이용해서 전체 추가
    : "name"은 제외하기때문에 null값으로 둔다.
@Override
public List<Item> selectListItem() {
    try {
        Bson filter = Filters.eq("_id", 1);
        Bson projection = Projections.exclude("name");
        FindIterable<Document> document = this.collection.find()
            .projection(projection)
            .sort(filter);
        List<Item> list = new ArrayList<>();
        for(Document tmp : document) {
            Item item = new Item(
                tmp.getLong("_id"), 
                null,
                tmp.getLong("price"), 
                tmp.getLong("quantity") 
            );
            list.add(item);
        }        
        return list;        
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

6. 페이지별 조회

  1. skip(skip) 사용
    : page는 (AppItem.java에서)파라미터로 들어옴
    : int skip = (page - 1) * 10;
    페이지 1 => 0, 10
    페이지 2 => 10, 10
    페이지 3 => 20, 10
  2. limit(limit) 사용
    : int limit = 10;
    : 한 페이지에 10개씩 표시
@Override
public List<Item> selectListPageItem(int page) {

    try {
        Bson filter = Filters.eq("_id", 1);
        int skip = (page - 1) * 10;
        int limit = 10;
        FindIterable<Document> document = this.collection.find()
                .sort(filter)
                .skip(skip)
                .limit(limit);
        List<Item> list = new ArrayList<>();
        for (Document tmp : document) {
            Item item = new Item(
                    tmp.getLong("_id"),
                    tmp.getString("name"),
                    tmp.getLong("price"),
                    tmp.getLong("quantity"));
            list.add(item);
        }
        return list;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

AppItem.java

1. 추가

  1. Item.java에 생성자를 임의로 만들었음.
    : public Item(String name, long price, long quantity)
    : 이름, 가격, 수량 순으로 넣으면 됨.
public class AppItem {
    public static void main(String[] args) {
        ItemDB itemDB = new ItemDBImpl();
        Item item = new Item("name2", 3300L, 33L);
        int response = itemDB.insertItem(item);
        System.out.println("response ===> " + response);
        if (response == 1) {
            System.out.println("추가성공");
        } else {
            System.out.println("추가실패");
        }
    }
}

2. 삭제

  1. ItemDB.java와 ItemDBImpl.java에서 throws Exception 처리를 했기때문에 AppItem.java에서 예외처리를 해야함.
    : 예외처리 = try_catch
  2. ItemDB.java의 추상화된 메소드를 불러오면 메소드에 예외처리하라는 경고가 뜸
    : Surround with try/catch 메뉴로 try_catch를 자동생성
public class AppItem {
    public static void main(String[] args) {
    	ItemDB itemDB = new ItemDBImpl();
        long code = 10016L;
        try {
            // Surround with try/catch 하면 묶음
            int result = itemDB.deleteItem(code);
            if (result == 1) {
                System.out.println("삭제성공");
            } else {
                System.out.println("삭제실패");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. 수정

public class AppItem {
    public static void main(String[] args) {
    	ItemDB itemDB = new ItemDBImpl();
        Item item = new Item();
        item.setId(10013L);
        item.setName("수정이름");
        item.setPrice(2500);
        item.setQuantity(25);
        int response = itemDB.updateItem(item);
        if (response == 1) {
            System.out.println("수정성공");
        } else {
            System.out.println("수정실패");
        }
    }
}

4. 한개조회

4-1. Map

  1. Collection 하위에 Map롸 List가 있음
  2. Map과 List 비교
    2-1. Map
    : ex) 문자 ["aaa", "bbb", 36]
    : 순차적인 데이터 처리(출력)에 용이하다.
    : 단점 - key가 없어서 36이 나이인지 수량인지 알기 어렵다.
    2-2 . List
    : ex) JSON비슷 {"ID":"aaa", "NAME":"bbb", "AGE":36}
    : 순차적X, key를 이용해서 넣어둠
    : 하나하나를 콕 집어내기에 용이
    : 단점 - 유연한 데이터 처리가 힘들다
public class AppItem {
    public static void main(String[] args) {
    	ItemDB itemDB = new ItemDBImpl();
        long code = 10013L;
        Map<String, Object> response = itemDB.selectOneMapItem(code);
        System.out.println(response.get("ID"));
        System.out.println(response.get("NAME"));
        System.out.println(response.get("PRICE"));
        System.out.println(response.get("QUANTITY"));
        System.out.println("response ===> " + response);
    }
}

4-2. Class(Item)

public class AppItem {
    public static void main(String[] args) {
    	ItemDB itemDB = new ItemDBImpl();
        long code = 10013L;
        Item response = itemDB.selectOneItem(code);
        if (response != null) {
            System.out.println(response.getId());
            System.out.println(response.getName());
            System.out.println(response.getPrice());
            System.out.println(response.getQuantity());
            System.out.println("조회성공 : " + response.toString());
        } else {
            System.out.println("조회실패");
        }
    }
}

5. 전체 조회 - name 제외

  1. response를 찍으면
    : [Item(), Item(), Item()] 이런 형식으로 나옴
  2. for문을 돌려서 하나씩 꺼내옴
    : for (Item tmp : response) { System.out.println(tmp.toString()); }
    : 아래와 같은 형식으로 나옴
    Item()
    Item()
    Item()
public class AppItem {
    public static void main(String[] args) {
    	ItemDB itemDB = new ItemDBImpl();
        List<Item> response = itemDB.selectListItem();
        System.out.println("response ===> " + response);
        for (Item tmp : response) {
            System.out.println(tmp.toString());
        }
    }
}

6. 페이지별 조회

  1. page 값을 int로 정의한다.
    : int page = 2;
  2. ItemDB의 생성자 => ItemDBImpl에서 사용 => selectListPageItem(page) 메소드
    : 파라미터 page로 값을 던짐
public class AppItem {
    public static void main(String[] args) {
        ItemDB itemDB = new ItemDBImpl();
        int page = 2;
        List<Item> response = itemDB.selectListPageItem(page);
        // System.out.println("response ===> " + response);
        for (Item tmp : response) {
            System.out.println(tmp.toString());
        }
    }
}
profile
The best

0개의 댓글