Java Data Objects(JDO)

を使用して、GAEデータストアでCRUDを実行するには、次のコードスニペットを参照してください。

JDOアノテーション

で顧客に注釈を付け、

PersistenceManager

を介してCRUDを実行してください。

追加

        Customer c = new Customer();
    c.setName(name);

    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
        pm.makePersistent(c);
    } finally {
        pm.close();
    }

検索

name == “mkyong”のところで “Customer”を検索してください。

    PersistenceManager pm = PMF.get().getPersistenceManager();

    Query q = pm.newQuery(Customer.class);
    q.setFilter("name == nameParameter");
    q.setOrdering("date desc");
    q.declareParameters("String nameParameter");

    try {
        List<Customer> results = (List<Customer>) q.execute("mkyong");
       //...
    } finally {
        q.closeAll();
        pm.close();
    }

名前== “mkyong”とメール== ”

[email protected]

“の “Customer”を検索してください。

    Query q = pm.newQuery(Customer.class);
    q.setOrdering("date desc");
    q.setFilter("name == nameParameter && email == emailParameter");
    q.declareParameters("String nameParameter, String emailParameter");

    try {
        List<Customer> results = (List<Customer>) q.execute("mkyong", "[email protected]");
       //...
    } finally {
        q.closeAll();
        pm.close();
    }

顧客レコードのリストを返します。

    PersistenceManager pm = PMF.get().getPersistenceManager();
    Query q = pm.newQuery(Customer.class);
    q.setOrdering("date desc");
    List<Customer> results = null;

    try {
        results = (List<Customer>) q.execute();
        if (!results.isEmpty()) {
           //good for listing
        }
    } finally {
        q.closeAll();
        pm.close();
    }

アップデート

更新するには、既存のオブジェクトを取得して変更します。

    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
        Customer c = pm.getObjectById(Customer.class, key);
        c.setName(name);
        c.setEmail(email);
        c.setDate(new Date());
    } finally {
        pm.close();
    }

削除

        PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
        Customer c = pm.getObjectById(Customer.class, key);
        pm.deletePersistent(c);
    } finally {
        pm.close();
    }

GAE + Spring MVC + CRUDの例

ここでは、JDOを使用してデータストアにデータを格納する、RESTスタイルのSpring MVCを使用して開発された単純なWebアプリケーションを示します。

  1. Google App Engine Java SDK 1.6.3.1、JDO 2.3

  2. Spring 3.1.1

  3. JDK 1.6

  4. Eclipse用Eclipse 3.7 Google Plugin

__P.S Google Plugin for Eclipseを使用してWebアプリケーションプロジェクトテンプレートを作成すると、自動的に `jdoconfig.xml`が作成され設定されます。

  • Note ** +この例では、JDOを使ってCRUDのみを実行する方法、DAOやBOなどのレイヤーを使用しない方法、成功または失敗したアクションの検証やメッセージ通知をできるだけシンプルにしています。

1.顧客

JDOアノテーションでCustomerオブジェクトに注釈を付ける。

package com.mkyong.model;

import java.util.Date;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;

@PersistenceCapable
public class Customer {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent
    private String name;

    @Persistent
    private String email;

    @Persistent
    private Date date;

   //getter and setter methods
}

2. PersistenceManager

シングルトンのPersistenceManagerクラスを作成します。

package com.mkyong;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;

public final class PMF {
    private static final PersistenceManagerFactory pmfInstance = JDOHelper
        .getPersistenceManagerFactory("transactions-optional");

    private PMF() {
    }

    public static PersistenceManagerFactory get() {
        return pmfInstance;
    }
}

3.スプリングコントローラ

Springコントローラ、RESTスタイルは、CRUD操作を実行します。コードは自明でなければなりません。


File:CustomerController.java

package com.mkyong.controller;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
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.mkyong.PMF;
import com.mkyong.model.Customer;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    @RequestMapping(value = "/add", 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");

        Customer c = new Customer();
        c.setName(name);
        c.setEmail(email);
        c.setDate(new Date());

        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(c);
        } finally {
            pm.close();
        }

        return new ModelAndView("redirect:list");

    }

    @RequestMapping(value = "/update/{name}", method = RequestMethod.GET)
    public String getUpdateCustomerPage(@PathVariable String name,
        HttpServletRequest request, ModelMap model) {

        PersistenceManager pm = PMF.get().getPersistenceManager();

        Query q = pm.newQuery(Customer.class);
        q.setFilter("name == nameParameter");
        q.setOrdering("date desc");
        q.declareParameters("String nameParameter");

        try {
            List<Customer> results = (List<Customer>) q.execute(name);

            if (results.isEmpty()) {
                model.addAttribute("customer", null);
            } else {
                model.addAttribute("customer", results.get(0));
            }
        } finally {
            q.closeAll();
            pm.close();
        }

        return "update";

    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ModelAndView update(HttpServletRequest request, ModelMap model) {

        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String key = request.getParameter("key");

        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {

            Customer c = pm.getObjectById(Customer.class, key);

            c.setName(name);
            c.setEmail(email);
            c.setDate(new Date());

        } finally {

            pm.close();
        }

       //return to list
        return new ModelAndView("redirect:list");

    }

    @RequestMapping(value = "/delete/{key}", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable String key,
            HttpServletRequest request, ModelMap model) {

        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {

            Customer c = pm.getObjectById(Customer.class, key);
            pm.deletePersistent(c);

        } finally {
            pm.close();
        }

       //return to list
        return new ModelAndView("redirect:../list");

    }

   //get all customers
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String listCustomer(ModelMap model) {

        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query q = pm.newQuery(Customer.class);
        q.setOrdering("date desc");

        List<Customer> results = null;

        try {
            results = (List<Customer>) q.execute();

            if (results.isEmpty()) {
                model.addAttribute("customerList", null);
            } else {
                model.addAttribute("customerList", results);
            }

        } finally {
            q.closeAll();
            pm.close();
        }

        return "list";

    }

}

4. JSPページ

JSPページで顧客を表示し、追加、更新、削除を実行します。


File:list.jsp

<%@ page import="java.util.List" %>
<%@ page import="com.mkyong.model.Customer" %>
<%@ page import="com.google.appengine.api.datastore.KeyFactory" %>
<html>
<body>
    <h1>GAE + Spring 3 MVC REST + CRUD Example with JDO</h1>

    Function : <a href="add">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>

        <%

        if(request.getAttribute("customerList")!=null){

            List<Customer> customers =
                           (List<Customer>)request.getAttribute("customerList");

            if(!customers.isEmpty()){
                 for(Customer c : customers){

        %>
                <tr>
                  <td><%=c.getName() %></td>
                  <td><%=c.getEmail() %></td>
                  <td><%=c.getDate() %></td>
                  <td><a href="update/<%=c.getName()%>">Update</a> |
                                      <a href="delete/<%=KeyFactory.keyToString(c.getKey()) %>">
                                       Delete</a>
                                  </td>
                </tr>
        <%

                }

            }

           }
        %>

        </tr>

    </table>

</body>
</html>


File:add.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"/></span></td>
            </tr>
            <tr>
                <td>Email :</td>
                <td><input type="text" style="width: 185px;" maxlength="30"
                    name="email" id="email"/></span></td>
            </tr>
        </table>
        <input type="submit" class="save" title="Save" value="Save"/>
    </form>

</body>
</html>


File:update.jsp

<%@ page import="com.mkyong.model.Customer" %>
<%@ page import="com.google.appengine.api.datastore.KeyFactory" %>
<html>
<body>
    <h1>Update Customer</h1>

    <%
        Customer customer = new Customer();

        if(request.getAttribute("customer")!=null){

            customer = (Customer)request.getAttribute("customer");

        }

    %>

    <form method="post" action="../update" >
        <input type="hidden" name="key" id="key"
            value="<%=KeyFactory.keyToString(customer.getKey()) %>"/>

        <table>
            <tr>
                <td>
                    UserName :
                </td>
                <td>
                    <input type="text" style="width: 185px;"
                                             maxlength="30" name="name" id="name"
                        value="<%=customer.getName() %>"/>
                </td>
            </tr>
            <tr>
                <td>
                    Email :
                </td>
                <td>
                    <input type="text" style="width: 185px;"
                                             maxlength="30" name="email" id="email"
                        value="<%=customer.getEmail() %>"/>
                </td>
            </tr>
        </table>
        <input type="submit" class="update" title="Update" value="Update"/>
    </form>

</body>
</html>

5.デモ

完了、Webアプリケーションのワークフローを示すデモをご覧ください。

{空} 1。既存の顧客のリストを表示するリストページ。


URL:http://localhost:8888/customer/list


gar jdo example、title = "gae-springmvc-1-jdo-list"、width = 599、height = 426

{空} 2。リスティングページで、[顧客の追加]リンクをクリックして表示します
顧客の追加ページ、新規顧客の入力、name = ”

mkyong

“、email
= ”


[email protected]


“をクリックし、 “追加”ボタンをクリックします。


URL:http://localhost:8888/customer/add


gar jdo example、title = "gae-springmvc-2-jdo-add"、width = 599、height = 426

{空} 3。顧客を保存すると、リスティングページに戻ります。


URL:http://localhost:8888/customer/list


gar jdo example、title = "gae-springmvc-3-jdo-list"、width = 599、height = 426

{空} 4。更新リンクを試すと、選択した顧客のデータが表示され、電子メールが「


[email protected]


」に更新され、更新ボタンをクリックします。


URL:http://localhost:8888/customer/update/mkyong


gar jdo example、title = "gae-springmvc-4-jdo-update"、width = 599、height = 426

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


URL:http://localhost:8888/customer/list


gar jdo example、title = "gae-springmvc-5-jdo-list"、width = 599、height = 426

{空} 6。顧客を削除するには、「削除」リンクをクリックしてください。

ソースコードをダウンロードする

ファイルサイズが大きいため、すべてのSpring MVCおよびGAE jarは除外されます。

ダウンロード:

GAE-SpringMVC-JDO-example.zip

(22 KB)