Google App Engine + Spring MVC、データストア低レベルAPIを使用したCRUDの例
低レベルAPIを使用して、Google App Engineデータストア、Java用のCRUDを実行するには、次のコードスニペットを参照してください。
追加
「名前」をキーとして顧客をデータストアに保管します。
Key customerKey = KeyFactory.createKey("Customer", "your name");
Entity customer = new Entity("Customer", customerKey);
customer.setProperty("name", "your name");
customer.setProperty("email", "your email");
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(customer);//save it
検索
10人の顧客をリストとして返します。
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query = new Query("Customer").addSort("date", Query.SortDirection.DESCENDING);
List<Entity> customers = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10));
一致するフィルタを使用して顧客を検索して返します。
Query query = new Query("Customer");
query.addFilter("name", FilterOperator.EQUAL, "your name");
PreparedQuery pq = datastore.prepare(query);
Entity customer = pq.asSingleEntity();
-
FilterOperator.EQUAL ** +このフィルタを再生すると、より小さい、より大きいなどの条件オプションはほとんどありません。
アップデート
更新するには、既存のエンティティを変更してもう一度保存します。
Query query = new Query("Customer");
query.addFilter("name", FilterOperator.EQUAL, "your name");
PreparedQuery pq = datastore.prepare(query);
Entity customer = pq.asSingleEntity();
customer.setProperty("name", name);
customer.setProperty("email", email);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(customer);//GAE will know save or update
削除
削除するには、エンティティキーが必要です。
Query query = new Query("Customer");
query.addFilter("name", FilterOperator.EQUAL, name);
PreparedQuery pq = datastore.prepare(query);
Entity customer = pq.asSingleEntity();
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.delete(customer.getKey());//delete it
GAE Spring MVC CRUDの例
ここで、Spring MVCをRESTスタイルで開発し、上記の低レベルのAPIを使用してGoogle App Engineデータストアのデータを操作する簡単なWebアプリケーションを紹介します。
-
Google App Engine Java SDK 1.6.3.1
-
Spring 3.1.1
-
JDK 1.6
-
Eclipse用Eclipse 3.7 Google Plugin
-
注意** この例では、CRUDのみの実行方法、DAOやBOなどのレイヤーの表示、成功または失敗したアクションの検証やメッセージ通知は表示されません。
-
1.スプリングコントローラ
Webページを表示してCRUDを実行するためのSpringコントローラ、RESTスタイルコードは自明でなければなりません。
File:CustomerController.java
package com.mkyong.controller;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
@Controller
@RequestMapping("/customer")
public class CustomerController {
@RequestMapping(value="/addCustomerPage", method = RequestMethod.GET)
public String getAddCustomerPage(ModelMap model) {
return "add";
}
@RequestMapping(value="/add", method = RequestMethod.POST)
public ModelAndView add(HttpServletRequest request, ModelMap model) {
String name = request.getParameter("name");
String email = request.getParameter("email");
Key customerKey = KeyFactory.createKey("Customer", name);
Date date = new Date();
Entity customer = new Entity("Customer", customerKey);
customer.setProperty("name", name);
customer.setProperty("email", email);
customer.setProperty("date", date);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(customer);
return new ModelAndView("redirect:list");
}
@RequestMapping(value="/update/{name}", method = RequestMethod.GET)
public String getUpdateCustomerPage(@PathVariable String name,
HttpServletRequest request, ModelMap model) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query = new Query("Customer");
query.addFilter("name", FilterOperator.EQUAL, name);
PreparedQuery pq = datastore.prepare(query);
Entity e = pq.asSingleEntity();
model.addAttribute("customer", e);
return "update";
}
@RequestMapping(value="/update", method = RequestMethod.POST)
public ModelAndView update(HttpServletRequest request, ModelMap model) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
String name = request.getParameter("name");
String email = request.getParameter("email");
String originalName = request.getParameter("originalName");
Query query = new Query("Customer");
query.addFilter("name", FilterOperator.EQUAL, originalName);
PreparedQuery pq = datastore.prepare(query);
Entity customer = pq.asSingleEntity();
customer.setProperty("name", name);
customer.setProperty("email", email);
customer.setProperty("date", new Date());
datastore.put(customer);
//return to list
return new ModelAndView("redirect:list");
}
@RequestMapping(value="/delete/{name}", method = RequestMethod.GET)
public ModelAndView delete(@PathVariable String name,
HttpServletRequest request, ModelMap model) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query = new Query("Customer");
query.addFilter("name", FilterOperator.EQUAL, name);
PreparedQuery pq = datastore.prepare(query);
Entity customer = pq.asSingleEntity();
datastore.delete(customer.getKey());
//return to list
return new ModelAndView("redirect:../list");
}
//get all customers
@RequestMapping(value="/list", method = RequestMethod.GET)
public String listCustomer(ModelMap model) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query =
new Query("Customer").addSort("date", Query.SortDirection.DESCENDING);
List<Entity> customers =
datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10));
model.addAttribute("customerList", customers);
return "list";
}
}
2. JSPページ
3 JSPページで顧客を表示し、追加および更新を実行します。
File:list.jsp
<%@ page import="java.util.List" %>
<%@ page import="com.google.appengine.api.datastore.Entity" %>
<html>
<body>
<h1>GAE + Spring 3 MVC REST + CRUD Example</h1>
Function : <a href="addCustomerPage">Add Customer</a>
<hr/>
<h2>All Customers</h2>
<table border="1">
<thead>
<tr>
<td>Name</td>
<td>Email</td>
<td>Created Date</td>
<td>Action</td>
</tr>
</thead>
<%
List<Entity> customers = (List<Entity>)request.getAttribute("customerList");
for(Entity e : customers){
%>
<tr>
<td><%=e.getProperty("name") %></td>
<td><%=e.getProperty("email") %></td>
<td><%=e.getProperty("date") %></td>
<td><a href="update/<%=e.getProperty("name")%>">Update</a>
| <a href="delete/<%=e.getProperty("name")%>">Delete</a></td>
</tr>
<%
}
%>
</table>
</body>
</html>
ファイル:and.jsp
<html>
<body>
<h1>Add Customer</h1>
<form method="post" action="add" >
<table>
<tr>
<td>
UserName :
</td>
<td>
<input type="text" style="width: 185px;"
maxlength="30" name="name" id="name"/>
</td>
</tr>
<tr>
<td>
Email :
</td>
<td>
<input type="text" style="width: 185px;"
maxlength="30" name="email" id="email"/>
</td>
</tr>
</table>
<input type="submit" class="save" title="Save" value="Save"/>
</form>
</body>
</html>
File:update.jsp
<%@ page import="com.google.appengine.api.datastore.Entity" %>
<html>
<body>
<h1>Update Customer</h1>
<%
Entity customer = (Entity)request.getAttribute("customer");
%>
<form method="post" action="../update" >
<input type="hidden" name="originalName" id="originalName"
value="<%=customer.getProperty("name") %>"/>
<table>
<tr>
<td>
UserName :
</td>
<td>
<input type="text" style="width: 185px;"
maxlength="30" name="name" id="name"
value="<%=customer.getProperty("name") %>"/>
</td>
</tr>
<tr>
<td>
Email :
</td>
<td>
<input type="text" style="width: 185px;"
maxlength="30" name="email" id="email"
value="<%=customer.getProperty("email") %>"/>
</td>
</tr>
</table>
<input type="submit" class="update" title="Update" value="Update"/>
</form>
</body>
</html>
3.春の設定
Springコントローラをスキャンし、ビューリゾルバを設定して、ビューをjspページにリダイレクトできるようにします。
File:mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.mkyong.controller"/>
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
4.春を統合する
SpringをWebアプリケーションに統合する。
File:web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app__2__5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app__2__5.xsd" version="2.5">
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
5.デモ
完了し、デモを見て、Webアプリケーションのワークフローを表示します。
{空} 1。既存の顧客のリストを表示するリストページ。
URL:http://localhost:8888/customer/list
画像://wp-content/uploads/2012/05/gae-springmvc-crud-list-1.png[gae spring mvc crudの例 – リスト、タイトル= “gae-springmvc-crud-list-1″、width = 600、高さ= 449]
{空} 2。リスティングページで、[顧客の追加]リンクをクリックして顧客追加ページを表示し、新しい顧客を記入して[追加]ボタンをクリックします。
URL:http://localhost:8888/customer/addCustomerPage

{空} 3。顧客を保存すると、リスティングページに戻ります。
URL:http://localhost:8888/customer/list

{空} 4。更新リンクを試すと、選択した顧客のデータが表示され、電子メールアドレスが更新され、更新ボタンがクリックされます。
URL:http://localhost:8888/customer/update/mkyong

{空} 5。電子メールが更新され、リスティングページにリダイレクトされます。
URL:http://localhost:8888/customer/list

{空} 6。顧客を削除するには、「削除」リンクをクリックしてください。
ソースコードをダウンロードする
ファイルサイズが大きいため、すべてのSpring MVCおよびGAE jarは除外されます。
ダウンロード:
GoogleAppEngine-SpringMVC-datastore.zip
(17 KB)
参考文献
: Using datastore].
https://developers.google.com/appengine/docs/java/datastore/entities
[GAE
: Entities].
https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/package-summary
[GAE
: datastore low-level api].
http://digitalsanctum.com/2009/07/02/google-app-engine-for-java-crud-with-jdo-spring-mvc/
[GAE
: CRUD Operations with JDO and Spring MVC].
http://www.hulstkamp.com/2011/04/12/experience-with-google-app-engine-spring-mvc-and-flex/
[Experience
Google App Engine、Spring MVC、Flexを使用して]