AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

POJO를 사용하여 데이터 모델링하기

이 가이드 에서는 Java Reactive Streams 운전자 사용하여 일반 Java 객체 또는 POJO로 모델링된 데이터를 저장 하고 조회 방법을 학습 수 있습니다. POJO는 비즈니스 로직을 데이터 표현과 분리하는 관행인 데이터 캡슐화에 자주 사용됩니다.

POJO에 대해 자세히 학습 Plain old Java 객체 위키백과 항목을 참조하세요.

이 가이드 다음 작업을 수행하는 방법을 보여줍니다.

  • POJO 직렬화 및 역직렬화를 위한 드라이버 구성

  • POJO로 모델링된 데이터를 사용하여 CRUD 작업 수행

중요

이 가이드 에서는 샘플 사용자 지정 구독자 구현 가이드 에 설명된 사용자 지정 Subscriber 구현을 사용합니다.

이 가이드 의 예제에서는 PersonAddress POJO 클래스를 사용하여 people라는 샘플 컬렉션 의 문서를 모델링합니다.

Person 클래스는 사람의 이름, 나이, 주소 저장합니다. 이 클래스의 정의는 다음과 같습니다.

import org.bson.types.ObjectId;
public final class Person {
private ObjectId id;
private String name;
private int age;
private Address address;
public Person() {}
public Person(final String name, final int age, final Address address) {
this.name = name;
this.age = age;
this.address = address;
}
public ObjectId getId() { return id; }
public void setId(final ObjectId id) { this.id = id; }
public String getName() { return name; }
public void setName(final String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(final int age) { this.age = age; }
public Address getAddress() { return address; }
public void setAddress(final Address address) { this.address = address; }
@Override
public String toString() {
return "Person{"
+ "id='" + id + "'"
+ ", name='" + name + "'"
+ ", age=" + age
+ ", address=" + address
+ "}";
}
}

Address 클래스는 거리, 도시 및 우편 번호를 저장합니다. 이 클래스의 정의는 다음과 같습니다.

public final class Address {
private String street;
private String city;
private String zip;
public Address() {}
public Address(final String street, final String city, final String zip) {
this.street = street;
this.city = city;
this.zip = zip;
}
public String getStreet() { return street; }
public void setStreet(final String street) { this.street = street; }
public String getCity() { return city; }
public void setCity(final String city) { this.city = city; }
public String getZip() { return zip; }
public void setZip(final String zip) { this.zip = zip; }
@Override
public String toString() {
return "Address{"
+ "street='" + street + "'"
+ ", city='" + city + "'"
+ ", zip='" + zip + "'"
+ "}";
}
}

POJO 클래스를 정의할 때는 다음 요구 사항을 충족하는지 확인하세요.

  • POJO 클래스는 프레임워크에서 클래스를 확장하거나 인터페이스를 구현할 수 없습니다.

  • 데이터를 저장 하고 조회 하려는 모든 필드를 포함하고 static 또는 transient(으)로 표시되지 않았는지 확인합니다.

  • JavaBean 명명 규칙에 따라 공용 getter 또는 setter 메서드를 포함하는 경우 운전자 데이터를 직렬화 또는 역직렬화할 때 해당 메서드를 호출합니다. 공개 필드 에 대한 getter 또는 setter 메서드를 생략하면 운전자 해당 메서드에 직접 액세스하거나 할당합니다.

Java Reactive Streams 운전자 와 함께 POJO를 사용하려면 먼저 사용자 지정 CodecRegistry를 생성하여 POJO를 직렬화 및 역직렬화하도록 POJO를 구성해야 합니다. 다음 단계에서는 CodecRegistry 를 만들어 클라이언트, 데이터베이스 또는 컬렉션 에 적용 방법을 보여 줍니다.

1

다음 코드는 PojoCodecProvider.Builder 클래스의 automatic(true) 설정을 사용하여 모든 클래스 및 해당 속성에 POJO 코덱을 자동으로 적용 .

CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
2

다음 코드에 표시된 대로 기본값 코덱 레지스트리를 PojoCodecProvider와 결합하는 CodecRegistry 를 만듭니다.

CodecRegistry pojoCodecRegistry = fromRegistries(
getDefaultCodecRegistry(),
fromProviders(pojoCodecProvider)
);

참고

요청된 클래스에 대한 코덱을 반환할 때까지 레지스트리를 순서대로 확인합니다. 기본값 코덱 레지스트리를 목록에 먼저 포함하고 PojoCodecProvider 를 마지막에 포함하면 거의 모든 클래스에 코덱을 제공할 수 있으므로 마지막에 포함합니다.

3

사용자 지정 CodecRegistry을(를) 사용하도록 MongoClient, MongoDatabase 또는 MongoCollection 인스턴스 구성합니다. 다음 방법 중 하나로 코덱 레지스트리를 설정하다 수 있습니다.

  1. MongoClient에서 CodecRegistry 를 설정합니다.

    MongoClientSettings settings = MongoClientSettings.builder()
    .codecRegistry(pojoCodecRegistry)
    .build();
  2. MongoDatabase에서 CodecRegistry 를 설정합니다.

    MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(pojoCodecRegistry);
  3. MongoCollection에서 CodecRegistry 를 설정합니다.

    MongoCollection<org.bson.Document> rawCollection = database.getCollection("people").withCodecRegistry(pojoCodecRegistry);
4

다음 코드와 같이 POJO 클래스를 getCollection() 문서 클래스 매개 변수로 전달하고 이를 MongoCollection 인스턴스 의 유형 인수로 지정합니다.

MongoCollection<Person> collection = database.getCollection("people", Person.class);

Person POJO를 사용하도록 운전자 구성한 후에는 POJO로 모델링된 데이터에 대해 CRUD 작업을 수행할 수 있습니다.

코덱 레지스트리는 알 수 없는 클래스에 대해 POJO Codec 을 자동으로 생성하므로 예비 구성 없이 즉시 POJO를 사용할 수 있습니다.

컬렉션 에 단일 Person 를 삽입하려면 insertOne() 메서드를 호출하고 결과를 구독 . 다음 예시 ada 이라는 Person 인스턴스 people 컬렉션 에 삽입합니다.

Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
collection.insertOne(ada).subscribe(new OperationSubscriber<InsertOneResult>());

여러 개의 Person 인스턴스를 삽입하려면 다음 예시 와 같이 insertMany() 메서드를 호출하고 인스턴스 목록을 전달합니다.

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() 메서드를 사용합니다. 필터하다 객체 find() 메서드에 전달하여 특정 조건과 일치하는 문서를 조회 할 수 있습니다. 운전자 필터하다 객체를 만드는 데 사용할 수 있는 Filters 헬퍼 메서드를 제공합니다.

중요

POJO를 쿼리할 때는 POJO 속성 이름이 아닌 문서 필드 이름을 기준으로 쿼리 해야 합니다. 기본값 으로 동일하지만 운전자 POJO 속성 이름을 매핑하는 방법을 변경할 수 있습니다.

필터하다 와 일치하는 첫 번째 Person 인스턴스 조회 하려면 find() 작업 결과에 대해 first() 메서드를 호출합니다.

다음 예시 address.city 필드 값이 "Wimborne"인 첫 번째 Person 인스턴스 검색합니다.

collection.find(eq("address.city", "Wimborne"))
.first()
.subscribe(new PrintToStringSubscriber<>());
Person{id='...', name='Timothy Berners-Lee', age=61, address=Address{street='Colehill', city='Wimborne', zip='null'}}

필터하다 와 일치하는 모든 Person 인스턴스를 조회 하려면 find() 메서드를 호출하고 결과를 구독 .

다음 예시 age 필드 값이 30보다 큰 모든 Person 인스턴스 검색합니다.

collection.find(gt("age", 30)).subscribe(new PrintToStringSubscriber<>());
Person{id='...', name='Charles Babbage', age=45, address=Address{street='5 Devonshire Street', city='London', zip='W11'}}
Person{id='...', name='Timothy Berners-Lee', age=61, address=Address{street='Colehill', city='Wimborne', zip='null'}}

컬렉션 의 문서를 업데이트 하려면 updateOne()updateMany() 메서드를 사용합니다. 이러한 메서드에 다음 매개변수를 전달합니다.

  • 업데이트 할 문서 를 지정하는필터 객체 .

  • 수정 사항을 지정하는문서 업데이트합니다. 사용 가능한 연산자 목록을 보려면 MongoDB Server 매뉴얼에서 업데이트 연산자를 참조하세요.

업데이트 메서드는 수정된 문서 수를 포함하여 작업에 대한 정보를 제공하는 UpdateResult 유형을 반환합니다.

필터하다 와 일치하는 단일 Person 인스턴스 업데이트 하려면 updateOne() 메서드를 사용합니다.

다음 예시 age 필드 값을 23 로, name 필드 값을 "Ada Lovelace"로 설정하여 "Ada Byron" 이라는 Person 를 업데이트합니다.

collection.updateOne(
eq("name", "Ada Byron"),
combine(set("age", 23), set("name", "Ada Lovelace"))
).subscribe(new OperationSubscriber<>());

필터와 일치하는 모든 Person 인스턴스를 업데이트하려면 updateMany() 메서드를 사용합니다.

다음 예시 null이 아닌 zip 값이 있는 모든 Person 인스턴스에 대해 zip 필드 값을 null 로 설정합니다.

collection.updateMany(not(eq("zip", null)), set("zip", null))
.subscribe(new OperationSubscriber<>());

기존 Person 인스턴스 완전히 바꾸려면 replaceOne() 메서드를 사용합니다.

다음 예시 name 필드 값이 "Ada Lovelace"Person 인스턴스 ada 변수가 참조하는 Person 로 바꿉니다.

collection.replaceOne(eq("name", "Ada Lovelace"), ada)
.subscribe(new OperationSubscriber<>());

컬렉션 에서 문서를 삭제 하려면 deleteOne()deleteMany() 메서드를 사용합니다. 삭제 문서 와 일치하는 필터하다 객체 전달합니다.

삭제 메서드는 삭제된 문서 수를 포함하여 작업에 대한 정보를 제공하는 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<>());

이 가이드 에 언급된 CRUD 작업에 대해 자세히 학습 CRUD 작업 섹션을 참조하세요.

이 가이드 에 언급된 메서드 및 클래스에 대해 자세히 학습 다음 API 설명서를 참조하세요.