简体   繁体   中英

Why can't I add save more than 1 object in my LinkedList while using JDO?

I am using google app engine and JDO. In one of my servlets i am adding objects in a linkedlist and saving everything using persistence manager. Till the end of servlet it shows that everything is working fine. it appends the linkedlist ok. But when i try to fetch that linkedlist from datastore by using jsp page, i figure out that only one object is added to that linkedlist. Rest of the objects which i added in linkedlist are not saved in datastore. Why is it happening?
Thanks in advance. here is the code:

 public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {

  resp.setContentType("text/html");

  PersistenceManager pm = PMF.get().getPersistenceManager();
  try
  {
//.... 
    for(int j=0; j<coordinate.length; j++){
        if(j < locations.size()){
                locations.get(j).getCoordinate().setLatitude(coordinate[j].x);
                locations.get(j).getCoordinate().setLongitude(coordinate[j].y);                         
        }else{
                        loc.setLatitude(coordinate[j].x);
                        loc.setLongitude(coordinate[j].y);
                        locat.setCoordinate(loc);
                        locations.add(locat);
        }
                   System.out.println(locations.size());
    }
    }catch(Exception ex){
        System.out.println("Error fetching runs: " + ex);
    }final{
        pm.close();
    }
 }

Your code is not complete, so it's hard to be sure, but I suspect that you're basically doing this:

Location locat = new Location();
List<Location> locations = ...;
for (int j = 0; j < coordinate.length; j++) {
    // ...
    locat.setCoordinate(loc);
    locations.add(locat);
}

In Java, adding an object to a list doesn't make a copy from the object into the list. The list simply stores a reference to your object. So, at each iteration, you overwrite what you stored in the object at the previous iteration, and add a new reference to the same object in the list. At the end, the list contains N references to the exact same object.

So when the datastore stores the list in database, it notices that the list contains the same object duplicated n times, and only stored the object once.

You thus have to make a new location object at each iteration:

List<Location> locations = ...;
for (int j = 0; j < coordinate.length; j++) {
    // ...
    Location locat = new Location();
    locat.setCoordinate(loc);
    locations.add(locat);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM