John John - 7 months ago 84
Java Question

Spring Data MongoRepositories DtoInstantiatingConverter

I have

public class Employee
Long empCode;
String address;
// getters setters

I have written a query using Mongo Repositories like

public interface EmployeeRepository extends MongoRepository<Employee, Long>

List<Employee> findEmployeesByEmpCode(int empCode);

@Query(value="{ 'empCode' : ?0 }", fields="{ 'address' : 1}")
List<String> findAddressByEmpCode(int empCode);

The first query works but the second fails. It works only if I change the returned type of List to Employee.

The error at failure is

java.lang.IllegalArgumentException: [Assertion failed] - this argument is required; it must not be null
at org.springframework.util.Assert.notNull(
at org.springframework.util.Assert.notNull(

Obviously, it cannot work out how to convert the values from the contained Employee object to String.
How can I implement this ? Any example would be much appreciated.



The fields attribute is used to filter properties which are not set into your domain objects (Employee). It has not much to do with MongoDB projection mechanism.

In order to use projection here, see projections in the reference documentation.

You will have to create a projection interface:

interface AddressesProjection { String getAddress(); }

and change the repository method signature accordingly:

List<AddressesProjection> findByEmpCode(int empCode);

Projections declare a contract between the underlying type and the method signatures related to the exposed properties. Hence it is required to name getter methods according to the property name of the underlying type.

This is the closest you can get, afaik.