1

I have a native hibernate query that returns a list of objects to me, with a for loop I would like to populate a class list, but I do not laugh because the list is always populated by the last element. Where's the error?

This the code:

...
        List<Object[]> results = query.list();

        List<PackDisTask> packageDistTasks = new ArrayList<PackDisTask>();
        PackageDistributionTaskId taskId = new PackageDistributionTaskId();
        Object[] result = null;
        String r = "";

        for (int i = 0; i < results.size(); i++) {
            PackageDistributionTask pdt = new PackageDistributionTask();
            result = results.get(i);

            if (result[0] != null) {
                r = result[0].toString();
                taskId.setFkPackageDistribution(Integer.parseInt(r));
            }

            if (result[10] != null) {
                r = result[10].toString();
                taskId.setFkTaskType(Integer.parseInt(r));
            }

            pdt.setId(taskId);

            packageDistTasks.add(pdt);
        }
Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
Sergio
  • 138
  • 7
  • Please, Be a bit more descriptive what is wrong with your approach do you face an exception, Can you show a stacktrace? – Youans Jul 17 '19 at 16:11
  • Does `results` only contain one element? Then your query is probably wrong. – Michael Jul 17 '19 at 16:14
  • And you should use `pdt` instead of `taskId` in the for-loop. – Michael Jul 17 '19 at 16:15
  • 2
    You're using the same `taskId` object for each of `pdt` objects. Probably you should create new `PackageDistributionTaskId` for each `pdt`. – Dmitriy Popov Jul 17 '19 at 16:19
  • @Michel - Result contains 297 different elements as query on db – Sergio Jul 17 '19 at 17:26
  • @youyoo there are no exceptions . – Sergio Jul 17 '19 at 17:30
  • @Dmitriy Popov please can you explain me better, I can't see where I'm wrong. – Sergio Jul 17 '19 at 17:31
  • Since every element in the list is supposed to contain a **different** PackageDistributionTaskId, you need to create a **new** PackageDistributionTaskId at each iteration, inside the loop. You're currently creating a single instance, outside the loop. – JB Nizet Jul 17 '19 at 17:33
  • Yes, taskId, must be recreated every time, and put in to the for-loop it work. Thank you – Sergio Jul 18 '19 at 07:25

0 Answers0