Hi,
It is probably related to your other question regarding to using int as an @Id value. This section of the docs (How the '_id' field is handled in the mapping layer) goes over the conventions in terms of what is supported with using and Id field an generated values.
I presume in your case you were expecting the id field to be populated after a save. That will only work if the id field is of the type String, BigInteger or ObjectId. Those are the only types in which the automatically generated Mongo OID can be marshalled into. You can store an int value as the mongo _id value but you would need to assign it in the POJO first before saving.
So, either change your Id type to be String, BigInteger or ObjectId in the PostThread class or assign the id yourself before saving. We will change the code so than if an @Id field other than String,BigInteger, or ObjectId is passed to MongoTemplate for a save and it has a null value, an exception will be thrown. See this issue.
Here is some working code
Code:
PostThread pt = new PostThread();
pt.setCategoryId(1);
template.save(pt);
String id = pt.getId();
PostThread thread = template.findById(id, PostThread.class);
assertNotNull(thread);
System.out.println(thread);
thread = template.findOne(query(where("id").is(id)), PostThread.class);
assertNotNull(thread);
System.out.println(thread);
And PostThread is
Code:
public class PostThread {
@Override
public String toString() {
return "PostThread [id=" + id + ", categoryId=" + categoryId + "]";
}
private String id;
private int categoryId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
}
Note that in this case, since it is such a simple class, you don't even need to use the Spring mapping annotations.
Cheers,
Mark