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){
Sys开发者_StackOverflowtem.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);
}
精彩评论