Reputation: 23
I connected to a database and printed a list of results from a query, after a loop. Three records were returned as expected and stored in a variable.
Now, I tried to use that variable containing the three records in another class, however, only one of the records in the looped list was printed in that new class. The first two records were missing. Only the last one remained. Why would the size of a looped list decrease when called in another class?
@Data
public class ClassA{
Crud crud = new Crud();
static EntityManager entityManager;
private String dbDemo;
public void myMethodOne() {
entityManager = crud.begin();
Query query =
entityManager.createQuery("select b from Table b order by b.createdDateTime desc").setMaxResults(3); // give me three records
List<EntityClass> queryResultlist = query.getResultList();
for (EntityClass resultRow : queryResultlist) {
dbDemo = resultRow.getId();
System.out.println(dbDemo);
}
}
Output:
Test1 Test2 Test3
public class ClassB{
ClassA ca = new ClassA();
public void verifyMyMethodTwo() {
ca.myMethodOne();
System.out.println(ca.dbDemo());
}
}
Output:
Test3
Upvotes: 0
Views: 66
Reputation: 671
My Java is rusty, but the algorithm that @khan9797 is pointing out is:
dbDemo = ""
List<EntityClass> queryResultlist = query.getResultList();
for (EntityClass resultRow : queryResultlist) {
dbDemo = dbDemo.concat(resultRow.getId());
}
System.out.println(dbDemo);
The problem you encountered is that the dbDemo value takes on one value at a time, rather than collecting all of the return values into one. You need to concatenate them all into one variable, then output that variable (thus outside the loop), and allow it to be stored for access by a caller.
Note: You may need to insert a separator. I leave that as an exercise for the less rusty.
Upvotes: 2