【问题标题】:Why can't I add save more than 1 object in my LinkedList while using JDO?为什么我不能在使用 JDO 时在我的 LinkedList 中添加保存超过 1 个对象?
【发布时间】:2011-07-07 13:30:17
【问题描述】:

我正在使用谷歌应用引擎和 JDO。在我的一个 servlet 中,我在链表中​​添加对象并使用持久性管理器保存所有内容。直到 servlet 结束,它表明一切正常。它附加了链表确定。但是当我尝试使用 jsp 页面从数据存储中获取该链接列表时,我发现只有一个对象被添加到该链接列表中。我在链表中​​添加的其余对象未保存在数据存储中。为什么会这样?
提前致谢。 这是代码:

 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();
    }
 }

【问题讨论】:

  • 您的代码中可能存在错误。我会看第 142 行。
  • 我正在使用 println 语句观察值。当我在我的 servlet 末尾时,链表的大小就是我想要的。但是当我从数据存储中访问它时,就会出现这个问题。
  • 当然。如果您希望我们帮助您编写代码,请出示您的代码。我们没有水晶球。
  • 我用代码编辑了我的问题。请看一看。
  • 位置在哪里定义?它从何而来?定位在哪里定义?您确定没有多次将同一个 locat 对象添加到列表中,这可以解释数据存储区只存储一次吗?

标签: java google-app-engine jdo linked-list


【解决方案1】:

您的代码不完整,因此很难确定,但我怀疑您基本上是在这样做:

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

在 Java 中,将对象添加到列表不会将对象复制到列表中。该列表仅存储对您的对象的引用。因此,在每次迭代中,您都会覆盖在上一次迭代中存储在对象中的内容,并在列表中添加对同一对象的新引用。最后,列表包含对完全相同对象的 N 个引用。

所以当数据存储区将列表存储到数据库中时,它会注意到该列表包含重复n次的相同对象,并且只存储了一次。

因此,您必须在每次迭代时创建一个新的位置对象:

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

【讨论】:

    猜你喜欢
    • 2010-12-04
    • 2011-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多