2

我已经阅读了一些文档,但还不能与数据存储区通信......谁能给我一个在 GWT Web 应用程序中使用的示例项目/objectify 代码(我使用 eclipse)......只是一个简单的'使用 RPC 的 put' 和 'get' 动作应该做......或者,至少告诉我它是如何完成的

4

1 回答 1

3

了解如何使 objectify 起作用的最简单方法是重复David 的 Chandler 博客中的这篇文章中描述的所有步骤。如果您对 GWT、GAE(Java)、gwt-presenter、gin\guice 等感兴趣,那么整个博客几乎是必读的。在那里你会找到工作示例,但无论如何我将展示一个稍微高级的示例。

在包中shared定义您的实体/模型:

import javax.persistence.Embedded;
import javax.persistence.Id;
import com.google.gwt.user.client.rpc.IsSerializable;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Unindexed;

@Entity
public class MyEntry implements IsSerializable {
    // Objectify auto-generates Long IDs just like JDO / JPA
    @Id private Long id;
    @Unindexed private String text = "";
    @Embedded private Time start;

    // empty constructor for serialization
    public MyEntry () {
    }
    public MyEntry (Time start, String text) {
        super();
        this.text = tText;
        this.start = start;
    }
    /*constructors,getters,setters...*/
}

时间类(也是shared包)只包含一个字段毫秒:

@Entity  
public class Time implements IsSerializable, Comparable<Time> {
protected int msecs = -1;    
  //rest of code like in MyEntry 
}

将类ObjectifyDao从上面的链接复制到您的server.dao包中。然后专门为MyEntry制作DAO类——MyEntryDAO:

package com.myapp.server.dao;

import java.util.logging.Logger;

import com.googlecode.objectify.ObjectifyService;
import com.myapp.shared.MyEntryDao;

public class MyEntryDao extends ObjectifyDao<MyEntry>
{
    private static final Logger LOG = Logger.getLogger(MyEntryDao.class.getName());

    static
    {
        ObjectifyService.register(MyEntry.class);
    }

    public MyEntryDao()
    {
        super(MyEntry.class);
    }

}

最后我们可以向数据库(server包)发出请求:

public class FinallyDownloadingEntriesServlet extends HttpServlet {
      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/plain");
                //more code...
                resp.setHeader("Content-Disposition", "attachment; filename=\""+"MyFileName"+".txt\";");
        try {
            MyEntryDao = new MyEntryDao();
          /*query to get all MyEntries from datastore sorted by start Time*/
            ArrayList<MyEntry> entries = (ArrayList<MyEntry>) dao.ofy().query(MyEntry.class).order("start.msecs").list();

            PrintWriter out = resp.getWriter();
            int i = 0;
            for (MyEntry entry : entries) {
                ++i;
                out.println(i);
                out.println(entry.getStart() + entry.getText());
                out.println();
            }
        } finally {
            //catching exceptions
        }
    }
于 2011-03-20T21:19:52.810 回答