Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading