spring-data-mongodb
spring-data-mongodb copied to clipboard
MongoTemplate应当优化的两点
First, the background.
Recently I did a project and I wanted to use MongoTemplate
to query the data collection corresponding to a certain Entity, and then to convert it into a Dto type; and the fields in the Dto and the Entity were the same, so I hoped that MongoTemplate
would directly query a Document and convert it into a Dto instead of an Entity.
However, I looked at the MongoTemplate
source code, and found that it could not be realized for the reason below:
MongoTemple
should provide the following methods but it did not:
-
public <T, R> R findOne(Query query, Class<T> entityClass, String collectionName, Class<R> resultClass)
-
public <T, R> List<R> find(Query query, Class<T> entityClass, String collectionName, Class<R> resultClass)
-
public <T, R> R findById(Object id, Class<T> entityClass, String collectionName, Class<R> resultClass)
-
public <T, R> R findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass, String collectionName, Class<R> resultClass)
-
public <T, R> R findAndRemove(Query query, Class<T> entityClass, String collectionName, Class<R> resultClass)
-
public <T, R> List<R> findAll(Class<T> entityClass, String collectionName, Class<R> resultClass)
-
public <T, R> List<R> findAllAndRemove(Query query, Class<T> entityClass, String collectionName, Class<R> resultClass)
These methods will make MongoTemplate
more flexible.
The inner class or method modifiers in MongoTemplate
was inapporpriate.
A method is defined in MongoTemplate
, as follows:
protected <S, T> List<T> doFind(String collectionName, Document query, Document fields, Class<S> entityClass, CursorPreparer preparer, DocumentCallback<T> objectCallback)
This is a protected method, which should be allowed to be overridden by subclasses, but the parameter DocumentCallback
is the internal interface in MongoTemplate
, which is only visible to the package, This means that the protected method cannot be overridden by subclasses, which makes no sense.
Hope for an improved `MongoTemplate`.
Please report issues in English, thank you!
Please report issues in English, thank you!
I have reported it in English.
Thank you. We'll revisit the protected doFind(...) method. Meanwhile, have you checked the Fluent Template API? It allows to define the mapping source as well as target class for read/write ops
List<Jedi> all = template.find(SWCharacter.class)
.as(Jedi.class)
.matching(where(...
Thank you. We'll revisit the protected doFind(...) method. Meanwhile, have you checked the Fluent Template API? It allows to define the mapping source as well as target class for read/write ops
List<Jedi> all = template.find(SWCharacter.class) .as(Jedi.class) .matching(where(...
Thanks, I will try it.