I have a collection in MongoDB that has items like this one:
{
"_id" : ObjectId("53e4d31d1f6b66e5163962e3c"),
"name" : "bob",
"nestedObject" : {
"_id" : ObjectId("53f5a623cb5e4c1ed4f6ce67")
//more fields...
}
}
Java representation of this item looks following:
public class SomeObject {
@Id
private String id;
private String name;
private NestedObject nestedObject;
//getters and setters
}
The Repository interface is defined like this:
public interface SomeObjectRepository extends MongoRepository<SomeObject, String> {
public List<SomeObject> findByName(String name);
public List<SomeObject> findByNestedObjectId(String id);
//some other find functions
}
Now, findByName(String name)
is working as it should be, but findByNestedObjectId(String id)
returns nothing.
Question is: is it possible to find collection items by it's nested object's attribute using repository interface? If not, what is the recommended way to approach this problem? Is it possible without reimplementing whole repository?
Spring boot using spring data JPA even creates nested object query from method name. Therefore, if you are using spring boot or spring data JPA, you must know how queries are created specially if you have nested object structure. Spring data JPA provides repository abstraction and reduces the boiler plate code from persistence layers.
Therefore, if you are using spring boot or spring data JPA, you must know how queries are created specially if you have nested object structure. Spring data JPA provides repository abstraction and reduces the boiler plate code from persistence layers.
Spring data JPA provides repository abstraction and reduces the boiler plate code from persistence layers. As discussed in our previous blog Spring data Java beginner, we can define queries in two ways, Query annotation and Method name itself.
@Repository is a Spring annotation that indicates that the decorated class is a repository. A repository is a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects.
I've figured out how to solve this.
Change the parameter type to org.bson.types.ObjectId; from String
public List<SomeObject> findByNestedObjectId(ObjectId id);
and when you call it use
repositoryName.findByNestedObjectId(new ObjectId(theIdString));
Spring-data-mongodb
would not convert _id field to ObjectId type automatically in nested class on query operation. You should convert it manually. For example:
public List<SomeObject> findByNestedObjectId(String id) {
Query query = Query.query(new Criteria("nestedObject._id", convertToObjectId(id)));
return mongoTemplate.find(query, SomeObject.class);
}
Object convertToObjectId(Object id) {
if (id instanceof String && ObjectId.isValid(id)) {
return new ObjectId(id);
}
return id;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With