SlideShare a Scribd company logo
Introduction to Datastore
Assoc.Prof. Dr.Thanachart Numnonda
 Asst.Prof. Thanisa Kruawaisayawan

        www.imcinstitute.com
             July 2012
Agenda
What is DataStore?

Using DataStore

JPA in DataStore
What is DataStore?
What is Datastore?
Google App Engine Datastore is a schema-less persistence
  system, whose fundamental persistence unit is called Entity, c
  omposed by an immutable Key and a collection of mutable pr
  operties.
Entities can be created, updated, deleted, loaded by key and
  queried for properties values.
DataStore is consistent and transactional, with support to
  current transaction.
The DataStore
The Datastore is not a relational database nor a
 façade.
Relational database technology doesn’t scale
 horizontally
   – Connection pools, shared caching are a problem
The Datastore is one of many public APIs used for
 accessing Google’s
The DataStore
The DataStore
The DataStore : Operations
Transactions and Index are based on MegaTable.
File persistence it's done with Google File System
 (GFS).
It's distributed by Chubby, a lock service for loosely-
 coupled distributed systems.
BigTable
BigTable is a compressed, high performance, and
 proprietary database system built on Google File
 System (GFS), Chubby Lock Service, and a few other
 Google programs
Currently not distributed or used outside of Google.
BigTable development began in 2004. and is now used
 by a number of Google application Google Earth,
 Google Map, Gmail, Youtube, etc..
BigTable : Design
BigTable is a fast and extremely large-scale DBMS.
It is a sparse, distributed multi-dimensional sorted map,
 sharing characteristics of both row-oriented and column-
 oriented databases.
  sparse because only "not null" values are persisted
  distributed in Google cloud
  persistent on Google File System
  multidimensional in columns values
  ordered lexicographically by key
BigTable : Design
Tables are optimized for GFS by being split into
 multiple tablets - segments of the table.
BigTable is designed to scale into the petabyte.
Each table has multiple dimensions (one of which is a
 feld for time, allowing for versioning and garbage
 collection).
It allows an infnite number of rows and columns.
Google File System
GFS is a proprietary distributed fle system developed
 by Google.
It is designed to provide effcient, reliable access to
 data using large clusters of commodity hardware.
GFS grew out of an earlier Google effort, BigFiles,
 developed by Larry Page and Sergey Brin in the early
 days of Google, while it was still located in Stanford.
Using DataStore
DataStore Operations
Datastore operations are defned around entities (data
 models) which are objects with one or more properties
  Types: string, user, Boolean, and so on
  Entities may be recursive or self-referential
Entity relationships are one-to-many or many-to-many.
Entities may be fxed or grow as needed.
DataStore Storage Model
Every entity is of a particular kind
Entities in a kind need not have the same properties
  One entity may have different “columns” from another in
   the same kind!
Unique IDs are automatically assigned unless the user
 defnes a key_name
Compare DataStore with Others
DataStore Storage Model
Basic unit of storage is an Entity consisting of
   Kind (table)
   Key (primary key)
   Entity Group (partition)
   0..N typed Properties (columns)
Datastore Quotas
Each call to Datastore counts towards the quota
The amount of data cannot exceed the billable
      Includes properties and keys but not the indices
CPU and Datastore CPU time quotas apply
Using the Datastore
Applications may access the Datastore using the JDO
 or the JPA classes.
The JDO and JPA classes are abstracted using the
 DataNucleus API
  Open source
   Not very popular
   Support for Java standards
   Poor documentation
JPA in DataStore
Setting Up JPA
The JPA and datastore JARs must be in the app's
 war/WEB-INF/lib/ directory.
A confguration fle named persistence.xml must be in
 the app's war/WEB-INF/classes/META-INF/ directory,
A confguration fle tells JPA to use the App Engine
 datastore.
The appengine-api.jar must also be in the war/WEB-
 INF/lib/ directory.
persistence.xml: Example
<?xml version="1.0" encoding="UTF-8"?>
 <?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
 <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
   http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="thaijavaappPU" transaction-type="RESOURCE_LOCAL">
     <persistence-unit name="thaijavaappPU" transaction-type="RESOURCE_LOCAL">

  <provider>org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider
   <provider>org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider
  </provider>
   </provider>
   <non-jta-data-source/>
    <non-jta-data-source/>
  <properties>
   <properties>
      <property name="datanucleus.ConnectionURL" value="appengine"/>
       <property name="datanucleus.ConnectionURL" value="appengine"/>
      <property name="datanucleus.NontransactionalRead" value="true"/>
       <property name="datanucleus.NontransactionalRead" value="true"/>
      <property name="datanucleus.NontransactionalWrite" value="true"/>
       <property name="datanucleus.NontransactionalWrite" value="true"/>
    </properties>
     </properties>
  </persistence-unit>
   </persistence-unit>
</persistence>
 </persistence>
Getting an EntityManager Instance
An app interacts with JPA using an instance of the EntityManager.

import javax.persistence.EntityManagerFactory;
 import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
 import javax.persistence.Persistence;
public class EMF {{
 public class EMF

     private static final EntityManagerFactory emfInstance ==
      private static final EntityManagerFactory emfInstance
      Persistence.createEntityManagerFactory("transactions-optional");
       Persistence.createEntityManagerFactory("transactions-optional");

     public static EntityManagerFactory get() {{
      public static EntityManagerFactory get()
         return emfInstance;
          return emfInstance;
     }}
}}
Entity Class : Example
@Entity
 @Entity
public class GuestList implements Serializable {{
 public class GuestList implements Serializable
     ……
     @Id
      @Id
     private String id;
      private String id;

     @Basic
      @Basic
     private User author;
      private User author;
     private String content;
      private String content;
     @Temporal(javax.persistence.TemporalType.DATE)
      @Temporal(javax.persistence.TemporalType.DATE)
     private Date visitDate;
      private Date visitDate;
     ……
     // Getter and Setter methods
      // Getter and Setter methods
}}
Queries and Indices
A query operates on every entity of a given kind.
     Specify zero or more sort orders
     Specify zero or more flters on property values
Indices are defned in the App Engine confguration fles
     Results are fetched directly from these indices; no indices are
      created on the fly
     WEB-INF/datastore-indexes.xml - non-standard fles
Normalization is not recommended
     Optimization techniques for RDBMSs may result in poor
      Datastore performance!
Query : Example
EntityManager em == EMF.get().createEntityManager();
 EntityManager em    EMF.get().createEntityManager();
try {{
 try
     Query query == em.createQuery("SELECT oo FROM GuestList AS o");
      Query query    em.createQuery("SELECT    FROM GuestList AS o");
     @SuppressWarnings("unchecked")
      @SuppressWarnings("unchecked")
     List<GuestList> results == (List<GuestList>) query.getResultList();
      List<GuestList> results     (List<GuestList>) query.getResultList();
     for (Object obj :: results) {{
      for (Object obj    results)
              GuestList guest == (GuestList) obj;
               GuestList guest    (GuestList) obj;
         String nickname == guest.getAuthor().getNickname();
          String nickname    guest.getAuthor().getNickname();
         out.println(nickname ++ "" "" ++ guest.getId());
          out.println(nickname             guest.getId());
   }}
}} catch(Exception ex) {{
    catch(Exception ex)
     out.println(ex);
      out.println(ex);
}}
Entity Relationships
Models association between entities.
There are four types of relationship multiplicities:
     @OneToOne
     @OneToMany
     @ManyToOne
Supports unidirectional as well as bidirectional relationships
     Unidirectional relationship: Entity A references B, but B doesn't
      reference A.
Example : ManyToOne Mapping
Example : OneToMany Mapping
Transactions and Entity Groups
Transaction = Group of Datastore operations that either
 succeed or fail
Entity groups are required because all grouped entities are
 stored in the same Datastore node
An entity may be either created or modifed once per
 transaction
Transactions may fail if a different user or process tries an
 update in the same group at the same time
Users decide whether to retry or roll the transaction back
Transaction in JPA : Example
Book book == em.find(Book.class, "9780596156732");
 Book book    em.find(Book.class, "9780596156732");
BookReview bookReview == new BookReview();
 BookReview bookReview    new BookReview();
bookReview.rating == 5;
 bookReview.rating    5;
book.getBookReviews().add(bookReview);
 book.getBookReviews().add(bookReview);
Transaction txn == em.getTransaction();
 Transaction txn    em.getTransaction();
txn.begin();
 txn.begin();
try {{
 try
   book == em.merge(book);
    book    em.merge(book);
    txn.commit();
     txn.commit();
}} finally {{
    finally
     if (txn.isActive()) {{
      if (txn.isActive())
          txn.rollback();
           txn.rollback();
     }}
}}
Unsupported Features of JPA
Owned many-to-many relationships, and unowned
 relationships.
"Join" queries.
Aggregation queries (group by, having, sum, avg, max, min)
Polymorphic queries.
Resources
Google App Engine for Java HOWTO, Andrew Lombardi, Mar
 2010
The Softer Side Of Schemas, Max Ross, May 2009
Official Google App Engine Tutorial,
 http://code.google.com/appengine/docs/java/gettingstarted/
Programming Google App Engine, Don Sanderson, O'Reilly,
 2010
Thank you

   thananum@gmail.com
www.facebook.com/imcinstitute
   www.imcinstitute.com

More Related Content

PDF
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
PDF
Java Web Programming on Google Cloud Platform [1/3] : Google App Engine
PPT
Java EE 6 & Spring: A Lover's Quarrel
PPTX
Rest with Java EE 6 , Security , Backbone.js
ODP
springmvc-150923124312-lva1-app6892
PPTX
ADF Gold Nuggets (Oracle Open World 2011)
PDF
netbeans
PDF
Spring mvc
Java Web Programming on Google Cloud Platform [3/3] : Google Web Toolkit
Java Web Programming on Google Cloud Platform [1/3] : Google App Engine
Java EE 6 & Spring: A Lover's Quarrel
Rest with Java EE 6 , Security , Backbone.js
springmvc-150923124312-lva1-app6892
ADF Gold Nuggets (Oracle Open World 2011)
netbeans
Spring mvc

What's hot (18)

PDF
Suportando Aplicações Multi-tenancy com Java EE
PPT
Java EE and Spring Side-by-Side
PPTX
Integration of Backbone.js with Spring 3.1
ODP
Java Spring MVC Framework with AngularJS by Google and HTML5
PDF
Java Web Programming [3/9] : Servlet Advanced
PPTX
Spring MVC
PDF
Android intents-3 www.j2program.blogspot.com
PPT
CTS Conference Web 2.0 Tutorial Part 2
PPTX
Javatwo2012 java frameworkcomparison
PDF
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
KEY
MVC on the server and on the client
PPT
Spring MVC Basics
PPTX
4. jsp
PDF
Java Web Programming [8/9] : JSF and AJAX
PDF
Local storage in Web apps
PPT
Spring 3.x - Spring MVC
PPTX
Soa development using javascript
PDF
DataFX - JavaOne 2013
Suportando Aplicações Multi-tenancy com Java EE
Java EE and Spring Side-by-Side
Integration of Backbone.js with Spring 3.1
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Web Programming [3/9] : Servlet Advanced
Spring MVC
Android intents-3 www.j2program.blogspot.com
CTS Conference Web 2.0 Tutorial Part 2
Javatwo2012 java frameworkcomparison
OSGi and Spring Data for simple (Web) Application Development - Christian Bar...
MVC on the server and on the client
Spring MVC Basics
4. jsp
Java Web Programming [8/9] : JSF and AJAX
Local storage in Web apps
Spring 3.x - Spring MVC
Soa development using javascript
DataFX - JavaOne 2013
Ad

Viewers also liked (7)

PDF
คู่มือ Dropbox
PPT
Developing Java Web Applications In Google App Engine
PDF
บทความเรื่อง การใช้ Cloud Computing ในประเทศไทย
PDF
วิธีการประยุกต์ใช้ระบบ Cloud storage ของ Google Drive ในการบริหารจัดการข้อมูล
 
PDF
๋Java Web Programming on Cloud Computing using Google App Engine
PDF
Cloud Computing กับการใช้งานในองค์กรต่างๆ
PDF
การประยุกต์ใช้ Cloud Computing สำหรับองค์กร
คู่มือ Dropbox
Developing Java Web Applications In Google App Engine
บทความเรื่อง การใช้ Cloud Computing ในประเทศไทย
วิธีการประยุกต์ใช้ระบบ Cloud storage ของ Google Drive ในการบริหารจัดการข้อมูล
 
๋Java Web Programming on Cloud Computing using Google App Engine
Cloud Computing กับการใช้งานในองค์กรต่างๆ
การประยุกต์ใช้ Cloud Computing สำหรับองค์กร
Ad

Similar to Java Web Programming on Google Cloud Platform [2/3] : Datastore (20)

PDF
Introduction to Datastore
PPT
PPTX
Hibernate Training Session1
PPT
Patni Hibernate
PPTX
S03 hybrid app_and_gae_datastore_v1.0
PDF
.Net template solution architecture
PDF
Data access
PPTX
Hibernate
PDF
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
PPT
Slice: OpenJPA for Distributed Persistence
PPT
WPF and Databases
PPT
PDF
Spring data requery
PPT
YDP_API&MS_UNIT_IIIii8iiiiiiiii8iiii.ppt
PPT
YDP_API&MS_UNIT_hiii detail notes to understand api.ppt
PDF
What is struts_en
ODP
JavaEE Spring Seam
PPT
App Grid Dev With Coherence
PPT
Application Grid Dev with Coherence
PPT
App Grid Dev With Coherence
Introduction to Datastore
Hibernate Training Session1
Patni Hibernate
S03 hybrid app_and_gae_datastore_v1.0
.Net template solution architecture
Data access
Hibernate
Spring Boot Tutorial Part 2 (JPA&Hibernate) .pdf
Slice: OpenJPA for Distributed Persistence
WPF and Databases
Spring data requery
YDP_API&MS_UNIT_IIIii8iiiiiiiii8iiii.ppt
YDP_API&MS_UNIT_hiii detail notes to understand api.ppt
What is struts_en
JavaEE Spring Seam
App Grid Dev With Coherence
Application Grid Dev with Coherence
App Grid Dev With Coherence

More from IMC Institute (20)

PDF
นิตยสาร Digital Trends ฉบับที่ 14
PDF
Digital trends Vol 4 No. 13 Sep-Dec 2019
PDF
บทความ The evolution of AI
PDF
IT Trends eMagazine Vol 4. No.12
PDF
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
PDF
IT Trends 2019: Putting Digital Transformation to Work
PDF
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
PDF
IT Trends eMagazine Vol 4. No.11
PDF
แนวทางการทำ Digital transformation
PDF
บทความ The New Silicon Valley
PDF
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
PDF
แนวทางการทำ Digital transformation
PDF
The Power of Big Data for a new economy (Sample)
PDF
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
PDF
IT Trends eMagazine Vol 3. No.9
PDF
Thailand software & software market survey 2016
PPTX
Developing Business Blockchain Applications on Hyperledger
PDF
Digital transformation @thanachart.org
PDF
บทความ Big Data จากบล็อก thanachart.org
PDF
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation
นิตยสาร Digital Trends ฉบับที่ 14
Digital trends Vol 4 No. 13 Sep-Dec 2019
บทความ The evolution of AI
IT Trends eMagazine Vol 4. No.12
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
IT Trends 2019: Putting Digital Transformation to Work
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
IT Trends eMagazine Vol 4. No.11
แนวทางการทำ Digital transformation
บทความ The New Silicon Valley
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
แนวทางการทำ Digital transformation
The Power of Big Data for a new economy (Sample)
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
IT Trends eMagazine Vol 3. No.9
Thailand software & software market survey 2016
Developing Business Blockchain Applications on Hyperledger
Digital transformation @thanachart.org
บทความ Big Data จากบล็อก thanachart.org
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation

Recently uploaded (20)

PPTX
How Much Does It Cost to Build a Train Ticket App like Trenitalia in Italy.pptx
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
Event Presentation Google Cloud Next Extended 2025
PDF
Smarter Business Operations Powered by IoT Remote Monitoring
PDF
Top Generative AI Tools for Patent Drafting in 2025.pdf
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
Dell Pro 14 Plus: Be better prepared for what’s coming
PDF
Software Development Methodologies in 2025
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
PDF
DevOps & Developer Experience Summer BBQ
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
PDF
Google’s NotebookLM Unveils Video Overviews
How Much Does It Cost to Build a Train Ticket App like Trenitalia in Italy.pptx
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
NewMind AI Monthly Chronicles - July 2025
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Transforming Manufacturing operations through Intelligent Integrations
Event Presentation Google Cloud Next Extended 2025
Smarter Business Operations Powered by IoT Remote Monitoring
Top Generative AI Tools for Patent Drafting in 2025.pdf
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Dell Pro 14 Plus: Be better prepared for what’s coming
Software Development Methodologies in 2025
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
DevOps & Developer Experience Summer BBQ
agentic-ai-and-the-future-of-autonomous-systems.pdf
Reimagining Insurance: Connected Data for Confident Decisions.pdf
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Google’s NotebookLM Unveils Video Overviews

Java Web Programming on Google Cloud Platform [2/3] : Datastore

  • 1. Introduction to Datastore Assoc.Prof. Dr.Thanachart Numnonda Asst.Prof. Thanisa Kruawaisayawan www.imcinstitute.com July 2012
  • 2. Agenda What is DataStore? Using DataStore JPA in DataStore
  • 4. What is Datastore? Google App Engine Datastore is a schema-less persistence system, whose fundamental persistence unit is called Entity, c omposed by an immutable Key and a collection of mutable pr operties. Entities can be created, updated, deleted, loaded by key and queried for properties values. DataStore is consistent and transactional, with support to current transaction.
  • 5. The DataStore The Datastore is not a relational database nor a façade. Relational database technology doesn’t scale horizontally – Connection pools, shared caching are a problem The Datastore is one of many public APIs used for accessing Google’s
  • 8. The DataStore : Operations Transactions and Index are based on MegaTable. File persistence it's done with Google File System (GFS). It's distributed by Chubby, a lock service for loosely- coupled distributed systems.
  • 9. BigTable BigTable is a compressed, high performance, and proprietary database system built on Google File System (GFS), Chubby Lock Service, and a few other Google programs Currently not distributed or used outside of Google. BigTable development began in 2004. and is now used by a number of Google application Google Earth, Google Map, Gmail, Youtube, etc..
  • 10. BigTable : Design BigTable is a fast and extremely large-scale DBMS. It is a sparse, distributed multi-dimensional sorted map, sharing characteristics of both row-oriented and column- oriented databases. sparse because only "not null" values are persisted distributed in Google cloud persistent on Google File System multidimensional in columns values ordered lexicographically by key
  • 11. BigTable : Design Tables are optimized for GFS by being split into multiple tablets - segments of the table. BigTable is designed to scale into the petabyte. Each table has multiple dimensions (one of which is a feld for time, allowing for versioning and garbage collection). It allows an infnite number of rows and columns.
  • 12. Google File System GFS is a proprietary distributed fle system developed by Google. It is designed to provide effcient, reliable access to data using large clusters of commodity hardware. GFS grew out of an earlier Google effort, BigFiles, developed by Larry Page and Sergey Brin in the early days of Google, while it was still located in Stanford.
  • 14. DataStore Operations Datastore operations are defned around entities (data models) which are objects with one or more properties Types: string, user, Boolean, and so on Entities may be recursive or self-referential Entity relationships are one-to-many or many-to-many. Entities may be fxed or grow as needed.
  • 15. DataStore Storage Model Every entity is of a particular kind Entities in a kind need not have the same properties One entity may have different “columns” from another in the same kind! Unique IDs are automatically assigned unless the user defnes a key_name
  • 17. DataStore Storage Model Basic unit of storage is an Entity consisting of Kind (table) Key (primary key) Entity Group (partition) 0..N typed Properties (columns)
  • 18. Datastore Quotas Each call to Datastore counts towards the quota The amount of data cannot exceed the billable  Includes properties and keys but not the indices CPU and Datastore CPU time quotas apply
  • 19. Using the Datastore Applications may access the Datastore using the JDO or the JPA classes. The JDO and JPA classes are abstracted using the DataNucleus API Open source  Not very popular  Support for Java standards  Poor documentation
  • 21. Setting Up JPA The JPA and datastore JARs must be in the app's war/WEB-INF/lib/ directory. A confguration fle named persistence.xml must be in the app's war/WEB-INF/classes/META-INF/ directory, A confguration fle tells JPA to use the App Engine datastore. The appengine-api.jar must also be in the war/WEB- INF/lib/ directory.
  • 22. persistence.xml: Example <?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="thaijavaappPU" transaction-type="RESOURCE_LOCAL"> <persistence-unit name="thaijavaappPU" transaction-type="RESOURCE_LOCAL"> <provider>org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider <provider>org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider </provider> </provider> <non-jta-data-source/> <non-jta-data-source/> <properties> <properties> <property name="datanucleus.ConnectionURL" value="appengine"/> <property name="datanucleus.ConnectionURL" value="appengine"/> <property name="datanucleus.NontransactionalRead" value="true"/> <property name="datanucleus.NontransactionalRead" value="true"/> <property name="datanucleus.NontransactionalWrite" value="true"/> <property name="datanucleus.NontransactionalWrite" value="true"/> </properties> </properties> </persistence-unit> </persistence-unit> </persistence> </persistence>
  • 23. Getting an EntityManager Instance An app interacts with JPA using an instance of the EntityManager. import javax.persistence.EntityManagerFactory; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Persistence; public class EMF {{ public class EMF private static final EntityManagerFactory emfInstance == private static final EntityManagerFactory emfInstance Persistence.createEntityManagerFactory("transactions-optional"); Persistence.createEntityManagerFactory("transactions-optional"); public static EntityManagerFactory get() {{ public static EntityManagerFactory get() return emfInstance; return emfInstance; }} }}
  • 24. Entity Class : Example @Entity @Entity public class GuestList implements Serializable {{ public class GuestList implements Serializable …… @Id @Id private String id; private String id; @Basic @Basic private User author; private User author; private String content; private String content; @Temporal(javax.persistence.TemporalType.DATE) @Temporal(javax.persistence.TemporalType.DATE) private Date visitDate; private Date visitDate; …… // Getter and Setter methods // Getter and Setter methods }}
  • 25. Queries and Indices A query operates on every entity of a given kind. Specify zero or more sort orders Specify zero or more flters on property values Indices are defned in the App Engine confguration fles Results are fetched directly from these indices; no indices are created on the fly WEB-INF/datastore-indexes.xml - non-standard fles Normalization is not recommended Optimization techniques for RDBMSs may result in poor Datastore performance!
  • 26. Query : Example EntityManager em == EMF.get().createEntityManager(); EntityManager em EMF.get().createEntityManager(); try {{ try Query query == em.createQuery("SELECT oo FROM GuestList AS o"); Query query em.createQuery("SELECT FROM GuestList AS o"); @SuppressWarnings("unchecked") @SuppressWarnings("unchecked") List<GuestList> results == (List<GuestList>) query.getResultList(); List<GuestList> results (List<GuestList>) query.getResultList(); for (Object obj :: results) {{ for (Object obj results) GuestList guest == (GuestList) obj; GuestList guest (GuestList) obj; String nickname == guest.getAuthor().getNickname(); String nickname guest.getAuthor().getNickname(); out.println(nickname ++ "" "" ++ guest.getId()); out.println(nickname guest.getId()); }} }} catch(Exception ex) {{ catch(Exception ex) out.println(ex); out.println(ex); }}
  • 27. Entity Relationships Models association between entities. There are four types of relationship multiplicities: @OneToOne @OneToMany @ManyToOne Supports unidirectional as well as bidirectional relationships Unidirectional relationship: Entity A references B, but B doesn't reference A.
  • 30. Transactions and Entity Groups Transaction = Group of Datastore operations that either succeed or fail Entity groups are required because all grouped entities are stored in the same Datastore node An entity may be either created or modifed once per transaction Transactions may fail if a different user or process tries an update in the same group at the same time Users decide whether to retry or roll the transaction back
  • 31. Transaction in JPA : Example Book book == em.find(Book.class, "9780596156732"); Book book em.find(Book.class, "9780596156732"); BookReview bookReview == new BookReview(); BookReview bookReview new BookReview(); bookReview.rating == 5; bookReview.rating 5; book.getBookReviews().add(bookReview); book.getBookReviews().add(bookReview); Transaction txn == em.getTransaction(); Transaction txn em.getTransaction(); txn.begin(); txn.begin(); try {{ try book == em.merge(book); book em.merge(book); txn.commit(); txn.commit(); }} finally {{ finally if (txn.isActive()) {{ if (txn.isActive()) txn.rollback(); txn.rollback(); }} }}
  • 32. Unsupported Features of JPA Owned many-to-many relationships, and unowned relationships. "Join" queries. Aggregation queries (group by, having, sum, avg, max, min) Polymorphic queries.
  • 33. Resources Google App Engine for Java HOWTO, Andrew Lombardi, Mar 2010 The Softer Side Of Schemas, Max Ross, May 2009 Official Google App Engine Tutorial, http://code.google.com/appengine/docs/java/gettingstarted/ Programming Google App Engine, Don Sanderson, O'Reilly, 2010
  • 34. Thank you [email protected] www.facebook.com/imcinstitute www.imcinstitute.com