업데이트하기

이태규·2022년 3월 12일
0

spring

목록 보기
9/64

물품 수정

    @Override
    public int updateItem(Item item) {

        try {
            Query query = new Query();
            Criteria criteria = Criteria.where("_id").is(item.getCode());
            query.addCriteria(criteria);

            Update update = new Update();

            update.set("name", item.getName());
            update.set("quantity", item.getQuantity());
            update.set("price", item.getPrice());

            if (item.getFilesize() > 0) {
                update.set("filesize", item.getFilesize());
                update.set("filename", item.getFilename());
                update.set("filedata", item.getFiledata());
                update.set("filetype", item.getFiletype());
            }

            UpdateResult result = mongodb.updateFirst(query, update, Item.class);
            if (result.getModifiedCount() == 1L) {
                return 1;
            }
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

위에서 어떤 타겟을 수정할 것인지 기준을 잡고

Query query = new Query();
            Criteria criteria = Criteria.where("_id").is(item.getCode());
            query.addCriteria(criteria);

어떤 것을 수정할 것인지 ("수정할 컬럼명", " 수정할 값") 정한다.

update.set("name", item.getName());
update.set("quantity", item.getQuantity());
update.set("price", item.getPrice());

UpdateResult result = mongodb.updateFirst(query, update, Item.class);
를 통해 업데이트 한다.

그리고 유효성 검사를 할 때
getModifiedCount와 getMatchedCount가 있는데,
getModifiedCount는 변경된 숫자이고,
getMatchedCount는 변경되지 않더라도 매치만 되면 된다

getModifiedCount로 했을 때 변경사항이 없으면 에러가 발생한다.

profile
한 걸음씩 나아가자

0개의 댓글