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

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

이 가이드에서는 일반 Java 객체로 모델링된 데이터를 저장하고 조회하는 데 사용할 Java Reactive Streams 드라이버를 학습할 수 있습니다. POJO는 데이터 표현에서 비즈니스 논리를 분리하는 인캡슐화에 자주 사용됩니다.

POJO에 대해 자세히 학습하려면 Plain Old Java 객체 Wikipedia 문서를 참조하세요.

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

  • 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를 직렬화하고 역직렬화하도록 구성해야 합니다. 다음 단계는 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

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

  1. MongoClientCodecRegistry 을(를) 설정합니다.

    MongoClientSettings settings = MongoClientSettings.builder()
    .codecRegistry(pojoCodecRegistry)
    .build();
  2. MongoDatabaseCodecRegistry 을(를) 설정합니다.

    MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(pojoCodecRegistry);
  3. MongoCollectionCodecRegistry 을(를) 설정합니다.

    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() 메서드를 호출하고 결과를 구독합니다. 다음 예제에서는 people 컬렉션에 ada 이라는 이름의 Person 인스턴스를 삽입합니다.

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 설명서를 참조하세요.