POJO CRUD 작업 예시
이 페이지의 내용
이 가이드 에서는 일반 Document
클래스 대신 일반 Java 객체(POJO)를 사용하여 문서를 모델링합니다.
이 가이드의 코드 예제는 PojoQuickTour.java 파일을 드라이버 소스 코드 Github 리포지토리에 저장합니다.
중요
이 가이드 에서는 샘플 사용자 지정 구독자 구현 가이드 에 설명된 사용자 지정
Subscriber
구현을 사용합니다.
전제 조건
이 가이드의 코드 예제를 실행하려면 다음 구성 요소를 설정해야 합니다.
MongoDB의 기본 포트에서 실행되는 MongoDB 서버(
27017
)프로젝트에 설치된 드라이버 종속성
다음 가져오기 문:
import com.mongodb.client.result.InsertOneResult; import com.mongodb.client.result.InsertManyResult; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoCollection; import com.mongodb.reactivestreams.client.MongoDatabase; import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.pojo.PojoCodecProvider; import java.util.List; import static com.mongodb.client.model.Filters.*; import static com.mongodb.client.model.Updates.*; import static java.util.Arrays.asList; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; POJO 클래스 정의. Github 의 드라이버 소스 리포지토리에서
Person
및Address
POJO의 전체 코드를 복사합니다.
사용자 지정 CodecRegistry 만들기
운전자 와 함께 POJO를 사용하려면 먼저 POJO에 대한 BSON 과의 변환을 처리하는 코덱을 포함하도록 CodecRegistry
를 구성해야 합니다. 이를 수행하는 가장 간단한 방법은 PojoCodecProvider.builder()
메서드를 사용하여 CodecProvider
을(를) 만들고 구성하는 것입니다.
다음 예에서는 기본 코덱 레지스트리를 POJO Codec
인스턴스를 자동으로 생성하도록 구성된 PojoCodecProvider
와 결합합니다.
CodecRegistry pojoCodecRegistry = fromRegistries( MongoClientSettings.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build()) );
참고
요청된 클래스에 대한 코덱을 반환할 때까지 레지스트리를 순서대로 확인합니다. DefaultCodecRegistry
는 목록에서 첫 번째여야 하고 PojoCodecProvider
은 거의 모든 클래스에 대한 코덱을 제공할 수 있으므로 항상 마지막 CodecProvider
여야 합니다.
CodecRegistry 사용
다음 목록에서는 pojoCodecRegistry
을(를) 사용하도록 설정하는 방법을 설명합니다.
MongoClient
객체 를 인스턴스화할 때 다음과 같이 설정합니다.MongoClientSettings settings = MongoClientSettings.builder() .codecRegistry(pojoCodecRegistry) .build(); MongoClient mongoClient = MongoClients.create(settings); 와
CodecRegistry
함께 대체 를MongoDatabase
사용합니다.database = database.withCodecRegistry(pojoCodecRegistry); 와
CodecRegistry
함께 대체 를MongoCollection
사용합니다.collection = collection.withCodecRegistry(pojoCodecRegistry);
MongoDB에 POJO 삽입
코덱 레지스트리는 알 수 없는 클래스에 대해 자동으로 POJO Codec
생성을 시도합니다. 이를 통해 예비 구성 없이 즉시 POJO를 사용할 수 있습니다.
MongoDB에 POJO를 삽입하려면 먼저 POJO 클래스로 구성된 MongoCollection
인스턴스를 만듭니다.
MongoCollection<Person> collection = database.getCollection("people", Person.class);
사람 인스턴스 삽입
컬렉션에 Person
를 삽입하려면 컬렉션 의 insertOne()
메서드를 사용합니다.
Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1")); collection.insertOne(ada).subscribe(new OperationSubscriber<InsertOneResult>());
여러 사람 인스턴스 삽입
여러 Person
인스턴스를 삽입하려면 Person
인스턴스 목록을 매개 변수로 사용하는 컬렉션의 insertMany()
메서드를 사용할 수 있습니다.
다음 예시 에서는 컬렉션 에 여러 Person
인스턴스를 추가합니다.
List<Person> people = asList( new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")), new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")), new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null)) ); collection.insertMany(people).subscribe(new OperationSubscriber<InsertManyResult>());
컬렉션 쿼리하기
컬렉션 을 쿼리 하려면 find()
메서드를 사용할 수 있습니다.
다음 예시 에서는 컬렉션 의 모든 Person
인스턴스를 출력합니다.
collection.find().subscribe(new PrintToStringSubscriber<>());
Person{id='...', name='Ada Byron', age=20, address=Address{street='St James Square', city='London', zip='W1'}} Person{id='...', name='Charles Babbage', age=45, address=Address{street='5 Devonshire Street', city='London', zip='W11'}} Person{id='...', name='Alan Turing', age=28, address=Address{street='Bletchley Hall', city='Bletchley Park', zip='MK12'}} Person{id='...', name='Timothy Berners-Lee', age=61, address=Address{street='Colehill', city='Wimborne', zip='null'}}
쿼리 필터 지정
특정 조건과 일치하는 Person
인스턴스를 쿼리하려면 필터 객체를 find()
메서드에 전달합니다. 필터 객체를 쉽게 만들 수 있도록 드라이버는 Filters
헬퍼 메서드를 제공합니다.
중요
POJO를 쿼리할 때는 POJO 속성 이름이 아닌 문서 필드 이름을 기준으로 쿼리 해야 합니다 . 기본값 동일하지만 POJO 속성 이름이 매핑되는 방식을 변경할 수 있습니다.
필터와 일치하는 한 사람 가져오기
다음 예에서는 eq()
필터 객체를 전달하여 동등 조건을 지정하여 데이터베이스에서 address.city
값이 Wimborne
인 첫 번째 Person
를 찾습니다.
collection.find(eq("address.city", "Wimborne")) .first() .subscribe(new PrintToStringSubscriber<>());
Person{id='591dbc2550852fa685b3ad1a', name='Timothy Berners-Lee', age=61, address=Address{street='Colehill', city='Wimborne', zip='null'}}
필터와 일치하는 모든 개인 인스턴스 가져오기
다음 예시 에서는 age
값이 30
보다 큰 모든 문서 를 인쇄합니다.
collection.find(gt("age", 30)).subscribe(new PrintToStringSubscriber<>());
문서 업데이트
컬렉션의 문서를 업데이트하려면 컬렉션의 updateOne()
및 updateMany()
메서드를 사용할 수 있습니다.
메서드에 다음 매개변수를 전달합니다.
업데이트할 문서를 결정하기 위해 객체를 필터링합니다. 빈 필터를 지정하고 모든
Person
인스턴스를 일치시키려면 빈Document
객체를 사용합니다.수정 사항을 지정하는 문서를 업데이트합니다. 사용 가능한 연산자 목록을 보려면 MongoDB Server 매뉴얼에서 업데이트 연산자 를 참조하세요.
업데이트 메서드는 업데이트로 수정된 문서 수를 포함하여 작업에 대한 정보를 제공하는 UpdateResult
유형을 반환합니다.
한 사람 업데이트
단일 Person
을(를) 업데이트하려면 updateOne()
메서드를 사용합니다.
다음 예시 에서는 Person
연령을 "Ada Byron"
23
로 설정하고 이름을 로 설정하여 라는 이름의 "Ada Lovelace"
를 업데이트합니다.
collection.updateOne( eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace")) ).subscribe(new OperationSubscriber<>());
여러 사람 인스턴스 업데이트
필터와 일치하는 모든 Person
인스턴스를 업데이트하려면 updateMany()
메서드를 사용합니다.
다음 예에서는 zip
값이 있는 모든 문서에 대해 zip
필드를 null
로 설정합니다.
collection.updateMany(not(eq("zip", null)), set("zip", null)) .subscribe(new OperationSubscriber<>());
한 사람 바꾸기
기존 Person
인스턴스를 변경하는 또 다른 방법은 replaceOne()
메서드를 사용하는 것입니다.
다음 예제에서는 Person
이라는 "Ada Lovelace"
Person
이름의 를 ada
앞의 insertOne 예제 에서변수가 참조하는 인스턴스로 바꿉니다.
collection.replaceOne(eq("name", "Ada Lovelace"), ada) .subscribe(new OperationSubscriber<>());
문서 삭제
컬렉션 에서 문서를 삭제 하려면 컬렉션의 deleteOne()
및 deleteMany()
메서드를 사용할 수 있습니다.
삭제 문서 와 일치하는 필터하다 객체 를 전달합니다. 빈 필터하다 를 지정하려면 빈 Document
객체 를 사용합니다.
삭제 메서드는 삭제된 문서 수를 포함하여 작업에 대한 정보를 제공하는 DeleteResult
유형을 반환합니다.
필터와 일치하는 한 사람 삭제
필터와 일치하는 단일 Person
를 삭제하려면 deleteOne()
메서드를 사용합니다.
다음 예에서는 address.city
값이 Wimborne
인 Person
하나를 삭제합니다.
collection.deleteOne(eq("address.city", "Wimborne")) .subscribe(new OperationSubscriber<>());
필터와 일치하는 모든 개인 인스턴스 삭제
필터와 일치하는 여러 Person
인스턴스를 삭제하려면 deleteMany()
메서드를 사용합니다.
다음 예시 에서는 address.city
값이 London
인 모든 Person
인스턴스를 삭제합니다.
collection.deleteMany(eq("address.city", "London")) .subscribe(new OperationSubscriber<>());