GWT-Objectify:基本的

时间:2011-03-20 18:11:25

标签: gwt objectify

我已经浏览了一些文档,但我还没能与数据存储区进行通信......任何人都可以给我一个示例项目/在GWT web应用程序中使用的客观化代码(我使用eclipse)...一个简单的'put'和'get'动作使用RPC应该......或者,至少告诉我它是如何完成的

1 个答案:

答案 0 :(得分:3)

了解如何使客观化工作的最简单方法是重复David's Chandler博客中this article中描述的所有步骤。如果您对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包)只包含一个字段msecs:

@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
        }
    }