เช่นเดียวกับ Repository implementation อื่นๆ ที่เราได้เห็นกันมา ยังมีข้อควรพิจารณาพื้นฐานบางอย่างที่ต้องจัดการอยู่ MongoDB implementation จริงๆ แล้วก็คล้ายกับของ Coherence มาก นี่คือภาพรวมระดับสูงของสิ่งที่เราต้องการ:

1. วิธี serialize Aggregate instance ออกเป็น MongoDB format แล้ว deserialize จาก format นั้นเพื่อประกอบ Aggregate instance กลับขึ้นมาใหม่ MongoDB ใช้ JSON ในรูปแบบพิเศษที่เรียกว่า BSON ซึ่งเป็น binary JSON format

2. identity ที่ไม่ซ้ำกันซึ่ง MongoDB สร้างขึ้นแล้วกำหนดให้กับ Aggregate นั้น

3. reference ไปยัง MongoDB node/cluster

4. collection ที่ไม่ซ้ำกันสำหรับเก็บ Aggregate type แต่ละแบบ โดย instance ทั้งหมดของ Aggregate type แต่ละแบบจะต้องถูกเก็บ เป็นชุดของ serialized document (key-value pairs) ใน collection ของตัวเอง

เรามาดูกันทีละขั้นตอนพร้อมกับไล่ดู Repository implementation จริงๆ สักตัว เนื่องจากเราจะใช้ ProductRepository อีกครั้ง คุณจึงเทียบ implementation ที่นี่กับของ Coherence (section ก่อนหน้า) ได้

public class MongoProductRepository
        extends MongoRepository<Product>
        implements ProductRepository {

    public MongoProductRepository() {
        super();

        this.serializer(new BSONSerializer<Product>(Product.class));
    }
    ...
}

implementation นี้ใช้ instance ของ BSONSerializer ตัวหนึ่งเพื่อ serialize และ deserialize Product instance ทั้งหมด (จริงๆ แล้ว instance นี้ถูกเก็บไว้ใน superclass MongoRepository ) ผมจะไม่ลงรายละเอียดเชิงลึกเกี่ยวกับ BSONSerializer มากนัก มันเป็น solution ที่พัฒนาขึ้นเองสำหรับสร้าง MongoDB DBObject instance จาก Product instance (รวมถึง Aggregate type อื่นๆ ด้วย) แล้วแปลงกลับเป็น Product instance ส่วน class นี้ให้มาพร้อมกับ sample code อื่นๆ

มีอะไรน่าสนใจหลายอย่างที่คุณทำได้กับ BSONSerializer การ serialization และ deserialization พื้นฐานจัดการผ่าน direct field access ซึ่งทำให้ domain object ของคุณไม่ต้อง implement JavaBean getter และ setter ซึ่งเป็นสิ่งที่คอยดึงให้คุณออกห่างจาก Anemic Domain Model [Fowler, Anemic] และเมื่อคุณไม่ใช้ method ในการเข้าถึง field แล้ว ในบางจุดคุณก็จำเป็นต้อง migrate จาก Aggregate type version หนึ่งไปยังอีก version หนึ่ง ซึ่งทำได้โดยการระบุ override mapping สำหรับแต่ละ field ตอน deserialization:

public class MongoProductRepository
        extends MongoRepository<Product>
        implements ProductRepository {

    public MongoProductRepository() {
        super();

        this.serializer(new BSONSerializer<Product>(Product.class));

        Map<String, String> overrides = new HashMap<String, String>();
        overrides.put("description", "summary");
        this.serializer().registerOverrideMappings(overrides);
    }
    ...
}

ในตัวอย่างนี้ เราจะสมมติว่า Product class รุ่นก่อนหน้านี้เคยมี field ชื่อ description แล้วในรุ่นถัดมา field นี้ถูกเปลี่ยนชื่อเป็น summary วิธีแก้ปัญหานี้วิธีหนึ่งคือการรัน migration script กับ MongoDB collection ทั้งหมดที่ใช้เก็บ Product instance ของแต่ละ tenant แต่การทำแบบนั้นอาจเป็นชุด operation ที่ทั้งยากและยาวนานมาก จนแทบจะนำไปใช้จริงไม่ได้ ทางเลือกอื่นคือเราจะขอให้ BSONSerializer map BSON field ใดๆ บน Product ที่ชื่อ description ไปยัง field ที่ชื่อ summary แทน จากนั้นเมื่อ Product ที่ถูก migrate แล้วทำ serialization กลับเป็น DBObject และบันทึกลงใน MongoDB collection การ serialization ครั้งใหม่ก็จะมี field ชื่อ summary แทนที่จะเป็น description แน่นอนว่ามันยังหมายความว่า Product instance ใดๆ ที่ไม่เคยถูกอ่านแล้วเขียนกลับลง store ก็จะยังมีชื่อ field ที่ล้าสมัยอย่าง description หลงเหลืออยู่ คุณต้องชั่งน้ำหนักข้อดีข้อเสียของแนวทาง lazy migration แบบนี้เอาเอง

ต่อไป เราต้องมีวิธีให้ MongoDB สร้าง identity ที่ไม่ซ้ำกันสำหรับ Aggregate instance แต่ละตัวเพื่อนำไปใช้:

public class MongoProductRepository
        extends MongoRepository<Product>
        implements ProductRepository {
    ...
    public ProductId nextIdentity() {
        return new ProductId(new ObjectId().toString());
    }
    ...
}

เรายังใช้ method nextIdentity() เหมือนเดิม แต่ใน implementation นี้เรา initialize ProductId ด้วยค่า String ของ ObjectId ตัวใหม่ เหตุผลหลักก็คือเราอยากให้ MongoDB ใช้ identity ที่ไม่ซ้ำกันตัวเดียวกับที่เราเก็บไว้ใน Aggregate instance เอง ดังนั้นเมื่อเราต้อง serialize Product (หรือ type อื่นใน Repository implementation อื่นๆ) เราก็สามารถขอให้ BSONSerializer map identity นั้นไปยัง key พิเศษของ MongoDB _id ได้:

public class BSONSerializer<T> {
    ...
    public DBObject serialize(T anObject) {
        DBObject serialization = this.toDBObject(anObject);

        return serialization;
    }

    public DBObject serialize(String aKey, T anObject) {
        DBObject serialization = this.serialize(anObject);

        serialization.put("_id", new ObjectId(aKey));

        return serialization;
    }
    ...
}

ส่วน method serialize() ตัวแรกไม่รองรับการ mapping แบบ _id ที่เห็นข้างต้น จึงเปิดทางให้ client เลือกได้ว่าจะคง identity ที่ตรงกันเอาไว้หรือไม่ ต่อไปมาดูกันว่า save() method นี้ถูก implement อย่างไร:

public class MongoProductRepository
        extends MongoRepository<Product>
        implements ProductRepository {
    ...
    @Override
    public void save(Product aProduct) {
        this.databaseCollection(
                this.collectionName(aProduct.tenantId()))
            .save(this.serialize(aProduct));
    }
    ...
}

เช่นเดียวกับ Coherence implementation ของ Repository interface ตัวเดียวกันนี้ เราจะได้ collection เฉพาะ tenant มาไว้ใช้เก็บ Product instance ของ TenantId ที่กำหนด ซึ่งการทำแบบนี้จะได้ Mongo DBCollection จาก DB มา และเพื่อให้ได้ object ของ DBCollection นั้นมาใช้ เราจึงมีโค้ดต่อไปนี้อยู่ใน MongoRepository abstract base class:

public abstract class MongoRepository<T> {
    ...
    protected DBCollection databaseCollection(
            String aDatabaseName,
            String aCollectionName) {
        return MongoDatabaseProvider
                .database(aDatabaseName)
                .getCollection(aCollectionName);
    }
    ...
}

เราใช้ MongoDatabaseProvider เพื่อขอ connection ไปยัง database instance ซึ่งจะตอบกลับมาเป็น DB object จากนั้น DB ที่ส่งกลับมานี้ เราก็จะขอ DBCollection จากมัน อย่างที่เห็นใน Repository implementation ตัวจริง ชื่อของ collection เกิดจากการรวมข้อความ "product" เข้ากับ identity เต็มรูปแบบของ tenant ส่วน Agile PM Context จะใช้ database เฉพาะตัวที่ชื่อ agilepm ซึ่งคล้ายกับวิธีที่ Coherence implementation ใช้ตั้งชื่อ cache ของตัวเอง:

public class MongoProductRepository
        extends MongoRepository<Product>
        implements ProductRepository {
    ...
    protected String collectionName(TenantId aTenantId) {
        return "product" + aTenantId.id();
    }

    protected String databaseName() {
        return "agilepm";
    }
    ...
}

เช่นเดียวกับ SpringHibernateSessionProvider ที่ได้กล่าวถึงก่อนหน้านี้ MongoDatabaseProvider ก็เป็นหนทางที่ใช้ดึง instance ของ DB ที่ใช้งานร่วมกันทั่วทั้ง application ออกมา

เราใช้ DBCollection ตัวเดียวกันนี้ทั้งใน save() และในการค้นหา Product instance:

public class MongoProductRepository
        extends MongoRepository<Product>
        implements ProductRepository {
    ...
    @Override
    public Collection<Product> allProductsOfTenant(
            TenantId aTenantId) {
        Collection<Product> products = new ArrayList<Product>();

        DBCursor cursor =
            this.databaseCollection(
                    this.databaseName(),
                    this.collectionName(aTenantId)).find();

        while (cursor.hasNext()) {
            DBObject dbObject = cursor.next();

            Product product = this.deserialize(dbObject);

            products.add(product);
        }

        return products;
    }

    @Override
    public Product productOfId(
            TenantId aTenantId, ProductId aProductId) {
        Product product = null;

        BasicDBObject query = new BasicDBObject();

        query.put("productId",
                new BasicDBObject("id", aProductId.id()));

        DBCursor cursor =
            this.databaseCollection(
                    this.databaseName(),
                    this.collectionName(aTenantId)).find(query);

        if (cursor.hasNext()) {
            product = this.deserialize(cursor.next());
        }

        return product;
    }
    ...
}

implementation ของ allProductsOfTenant() ก็คล้ายกับของ Coherence อีกเช่นกัน เราแค่ขอให้ DBCollection ของ tenant นั้นเรียก find() เพื่อดึง instance ทั้งหมดออกมา ส่วน productOfId() นั้น คราวนี้เราจะใช้ DBCollection เรียก method find() พร้อมกับส่ง DBObject ที่อธิบายถึง Product instance ที่ต้องการดึงมาโดยเฉพาะ ใน method finder ทั้งสองตัวนี้ เราใช้ DBCursor ที่ส่งกลับมาเพื่อดึงทั้งหมด และดึงเฉพาะ instance แรก ตามลำดับ