Search code examples
javaspringspring-bootjpahashmap

Map<String, Repository> Unexpected beheaviour


I'm trying to define a Map<String, DataTablesRepository> to map more than one JPA repository. This is my code

@Service
@AllArgsConstructor
public class MyDataTablesService {

    private final RegistroDtRepository registroDtRepository;
    private final ContinentiDtRepository continentiDtRepository;

    public Map<String, DataTablesRepository> repositories = this.createMap();

    public DataTablesOutput<?> findAllDatatable(String repoId, DataTablesInput input) {

        System.out.println(this.repositories);

        DataTablesRepository repository = this.repositories.get(repoId);

        DataTablesOutput<?> res = repository.findAll(input);
        return res;
    }

    private Map<String, DataTablesRepository> createMap(){
        Map<String, DataTablesRepository> myMap = new HashMap<String, DataTablesRepository>();
        myMap.put("continenti", this.continentiDtRepository);
        myMap.put("registro", this.registroDtRepository);
        return myMap;
    }
}

Calling the findAllDataTable method, the expected output should be something like this

{registro=org.springframework.data.jpa.datatables.repository.DataTablesRepositoryImpl@2aec0c10, continenti=org.springframework.data.jpa.datatables.repository.DataTablesRepositoryImpl@1bf71fb7}

Instead, in terminal, i have this:

{registroDtRepository=org.springframework.data.jpa.datatables.repository.DataTablesRepositoryImpl@2aec0c10, continentiDtRepository=org.springframework.data.jpa.datatables.repository.DataTablesRepositoryImpl@1bf71fb7}

So the map keys are not setted properly and, of course, this.repositories.get("continenti") returns null. What am I doing wrong?


Solution

  • you can explicitly set the desired keys when creating the map: here is the code to Initialize repositories map directly in the constructor:

    private final Map<String, DataTablesRepository> repositories;
    
    public MyDataTablesService(RegistroDtRepository registroDtRepository, ContinentiDtRepository continentiDtRepository) {
        this.registroDtRepository = registroDtRepository;
        this.continentiDtRepository = continentiDtRepository;
    
        this.repositories = createMap();
    }
    
    
    // and the rest of your code