max*_*axi 6 java spring mongodb spring-data
我正在使用 MongoRepository 接口为不同的实体扩展我的自定义存储库。现在我遇到了问题,让我们假设一个例子:我有 2 个实体:
@Document(collection = "person")
public class Employee {
private String position;
}
Run Code Online (Sandbox Code Playgroud)
和
@Document(collection = "person")
public class Manager {
private String major;
}
Run Code Online (Sandbox Code Playgroud)
两者的存储库:
@Repository
public interface ManagerRepository extends MongoRepository<Manager, String> {}
Run Code Online (Sandbox Code Playgroud)
和
@Repository
public interface EmployeeRepository extends MongoRepository<Employee, String> {}
Run Code Online (Sandbox Code Playgroud)
当我保存 2 个模型时,一切顺利:
{
"_id" : ObjectId("5541f988d4c603ebac18a147"),
"_class" : "com.igmtechnology.gravity.core.init.test.Manager",
"major" : "majority"
}
{
"_id" : ObjectId("5541f988d4c603ebac18a148"),
"_class" : "com.igmtechnology.gravity.core.init.test.Employee",
"position" : "developer"
}
Run Code Online (Sandbox Code Playgroud)
但是当我从其中一个存储库中执行 findAll() 时,我得到了 2 个对象,其中一个 spring 会自动转换为另一个对象。如何避免这种自动铸造?或者如何指定我需要获得哪个课程?
For both of the repositories, you can use the @Query annotation to specify a MongoDB JSON query string that will be used instead of query derived from the method's name (you must know that there's a convention for parsing the repository's method names and for building MongoDB queries).
So, by using @Query, you can do:
@Repository
public interface ManagerRepository extends MongoRepository<Employee, String>
@Query(value="{ '_class' : 'com.igmtechnology.gravity.core.init.test.Manager' }")
List<Person> findAllManagers();
}
Run Code Online (Sandbox Code Playgroud)
Behind the scenes, this will generate a query, similar to this one:
db.person.findAll({'_class' ; 'com.igmtechnology.gravity.core.init.test.Manager'});
Run Code Online (Sandbox Code Playgroud)
However, there's a minor problem with this code. If you change the fully-qualified class name of Manager, then the query would not throw a RuntimeException, but would return nothing. In this case you can use a wildcard within the @Query.
@Query(value="{ '_class' : ?0 }")
List<Person> findAllManagers(String className);
Run Code Online (Sandbox Code Playgroud)
Then, when you invoke the method, you can just do:
managerRepository.findAllManagers(Manager.class.getName());
Run Code Online (Sandbox Code Playgroud)
The provided Manager.class.getName() will replace the ?0 wildcard and your query will built properly.
Same goes for the Employee repository with the difference that you have to provide the fully-qualified class name of Employee in the @Query's value attribute.
More info:
| 归档时间: |
|
| 查看次数: |
1932 次 |
| 最近记录: |