ravindrab
ravindrab

Reputation: 2792

Spring mongotemplate query result with subDocuments

A document in productChanges collection looks like below.

{
    "_id" : NumberLong(9780876590034),
    "isbn" : NumberLong(9780876590034),
    "updDtime" : ISODate("2016-06-08T14:02:29.044Z"),
    "Audit" : {
        "LastProcCntrlNo" : 100192211,
        "UpdDtime" : ISODate("2016-06-08T14:02:29.044Z"),
        "AddDtime" : ISODate("2016-06-08T14:02:29.044Z")
    } 
}

I have my ProductChanges.java class

public class ProductChanges {
     Long isbn;
     Date updDtime;
     Audit audit;

     // getters & setters
}

I use mongoTemplate to query the DB, but I can't get Audit object populated.

// query the DB
List<ProductChanges> productChanges = mongoTemplate.find(query, ProductChanges.class, "productChanges");

This should be straightforward. Do I need to annotate my Audit object? Am I missing something trivial?

Spring Data MongoDB documentation was not helpful in finding an answer to this problem.

Upvotes: 1

Views: 1784

Answers (1)

Ali Dehghani
Ali Dehghani

Reputation: 48193

Based on the Spring Data MongoDB documentation:

The short Java class name is mapped to the collection name in the following manner. The class com.bigbank.SavingsAccount maps to savingsAccount collection name.

The fields of an object are used to convert to and from fields in the document. Public JavaBean properties are not used.

Since your sub-document field is named Audit and the Java field name is audit, Spring Data couldn't populate the audit field as you expected.

In order to fix this problem, you either should rename your field to Audit:

public class ProductChanges {
     Long isbn;
     Date updDtime;
     Audit Audit; // renamed to Audit from audit

     // getters & setters    
}

Or Use @Field annotation:

public class ProductChanges {
     Long isbn;
     Date updDtime;
     @Field("Audit") Audit audit;

     // getters & setters
}

You can read more about mapping annotations here. And a word of advice, try to use a consistent naming convention.

Upvotes: 1

Related Questions