Spring boot only returning one object

SAB :

I am getting multiple records from a database and want to return these values through a spring-boot API, I can get one value, but when multiple are returned from the database only the last record is being returned by the API

I have this model defined

@Data
public class TestModel {

/** Field rank. (value is "rank") */
private String rank;
/** Field category. (value is "category") */
private String category;
/** Field content. (value is "content") */
private String content;
private String date;
}

And within my controller I populate the repository like this:

private static void populateTestDetails(List<TestModel> testModels, List<Test> test) {
    TestModel testModel = new testModel();
    for (int i = 0; i < wellness.size(); i++) {
        if (test.get(i) != null) {
            Test testValue = test.get(i);

            testModel.setRank(testValue.getRank());
            testModel.setCategory(testValue.getCategory());
            testModel.setContent(testValue.getContent());
            testModel.setDate(testValue.getDate());


        } else {
            testModel.setRank("0");
            testModel.setCategory("null");
            testModel.setContent("0");
            testModel.setDate("null");
        }
    }
    testModels.add(testModel);
}

I'd guess my call is overwriting itself in the for loop, how would I append the results to an array? so the results would look like?

[{"rank":"1","category":"test","content":"2","date":"16/01/2020"}, 
{"rank":"2","category":"another test","content":"3","date":"16/01/2020"}]

I'm very new to JAVA, so apologies that my basic knowledge is lacking and terminology may be wrong

Simon Martinelli :

You are very close. You have to create the TestModel object in the for loop and also add it to the collection in the for loop (it doesn't matter if you add it at the beginning or the end)

private static void populateTestDetails(List<TestModel> testModels, List<Test> test) {
    for (int i = 0; i < wellness.size(); i++) {
        TestModel testModel = new testModel();
        testModels.add(testModel);

        if (test.get(i) != null) {
            Test testValue = test.get(i);

            testModel.setRank(testValue.getRank());
            testModel.setCategory(testValue.getCategory());
            testModel.setContent(testValue.getContent());
            testModel.setDate(testValue.getDate());


        } else {
            testModel.setRank("0");
            testModel.setCategory("null");
            testModel.setContent("0");
            testModel.setDate("null");
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19133&siteId=1