MANIPULATING DATA

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Objected Oriented Perl An introduction – because I don’t have the time or patience for an in- depth OOP lecture series…
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Road Map Introduction to object oriented programming. Classes
Fundamentals, Design, and Implementation, 9/e Chapter 11 Managing Databases with SQL Server 2000.
Copyright W. Howden1 Lecture 19: Intro to O/O Components.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Server Pages Russell Beale. What are Java Server Pages? Separates content from presentation Good to use when lots of HTML to be presented to user,
Managing Concurrency in Web Applications. DBI 2007 HUJI-CS 2 Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
Miscellaneous Excel Combining Excel and Access. – Importing, exporting and linking Parsing and manipulating data. 1.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
LiveCycle Data Services Introduction Part 2. Part 2? This is the second in our series on LiveCycle Data Services. If you missed our first presentation,
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Chapter 6 Server-side Programming: Java Servlets
CSCI 6962: Server-side Design and Programming Database Manipulation in ASP.
Forms and Server Side Includes. What are Forms? Forms are used to get user input We’ve all used them before. For example, ever had to sign up for courses.
BlackBerry Persistent Storage Models Persistent Storage APIs and Record Management System.
Data structures Abstract data types Java classes for Data structures and ADTs.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
MCS 270 Spring 2014 Object-Oriented Software Development.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
Object Oriented Analysis and Design Class and Object Diagrams.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
ADVANTAGES OF DATA BASE MANAGEMENT SYSTEM. TO BE DICUSSED... Advantages of Database Management System  Controlling Data RedundancyControlling Data Redundancy.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
INTRODUCTION lecture1 1. Data base concept Data is a meaningless static value. What does 3421 means? Information is the data you process in a manner that.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
C++ Inheritance Data Structures & OO Development I 1 Computer Science Dept Va Tech June 2007 © McQuain Generalization versus Abstraction Abstraction:simplify.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
IS-907 Java EE Introduction to JPA. Java Persistence API A framework for using relational databases in Java programs mapping between tables and classes,
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
Kyung Hee University Class Diagramming Notation OOSD 담당조교 석사과정 이정환.
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
Retele de senzori Curs 2 - 1st edition UNIVERSITATEA „ TRANSILVANIA ” DIN BRAŞOV FACULTATEA DE INGINERIE ELECTRICĂ ŞI ŞTIINŢA CALCULATOARELOR.
Using Datastore with JDO 1. Setting up DataNucleus Access Platform 2. JDO class enhancement 3. POJOs and JDO Annotations 4. PersistencyManager and its.
OOPSLA Lab1 Chapter 7 Java Binding Prof. Hyoung-Joo Kim OOPSLA Lab. Dept. of Computer Engineering Seoul National University.
Programming Logic and Design Seventh Edition
Phil Tayco Slide version 1.0 Created Sep 18, 2017
Andy Wang Object Oriented Programming in C++ COP 3330
Intro To Classes Review
COM components + persistent storage = objects
Creating Objects & String Class
More Object Oriented Programming
The super Reference Constructors cannot be used in child classes, even though they have public visibility Yet we often want to use the parent's constructor.
Overriding Methods & Class Hierarchies
Object Oriented Programming in java
Java Programming Language
Defining Classes and Methods
Review of Previous Lesson
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Presentation transcript:

MANIPULATING DATA

To manipulate data, you need a reference to the data… Welcome to Object keys Full Key = app engine application ID + separator + entity kind + separator + entity group + separator + entity ID key – Actually, each part is hashed before concatenation Typical ways to specify the entity ID key – You set it yourself as a String (or Long) – You let GAE automatically assign a Long – You let GAE automatically set an encoded String – You set it yourself as a custom Key object

Setting your own String as a key package edu.oregonstate.mobilecloud.lectures.clouddatastore; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import public class private String title; public String getTitle() { return title != null ? title : ""; } public void setTitle(String title) { this.title = title; } 2.Before trying to makePersistent, be sure to set the value 3.Any existing entity of that type with that key is overwritten 2.Before trying to makePersistent, be sure to set the value 3.Any existing entity of that type with that key is overwritten

Letting GAE automatically assign a Long key package edu.oregonstate.mobilecloud.lectures.clouddatastore; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import public class = IdGeneratorStrategy.IDENTITY) private Long id; public Long getID() { return id; } 2.Specify IDENTITY generator type 3.Do not try to assign the ID when instantiating object 2.Specify IDENTITY generator type 3.Do not try to assign the ID when instantiating object

Listing all entities of a certain kind <% PersistenceManager pm = PMF.getPMF().getPersistenceManager(); try { Query query = pm.newQuery(Test3Members.class); List allTest3 = (List )query.execute(); for (Test3Members obj : allTest3) { out.write(" "+obj.getDepartment()+obj.getCoursenum() +": difficulty "+obj.getDifficulty()+" "); out.write(" "+obj.getDescription()+" "); out.write(" "); } } finally { pm.close(); } %> 1.Create Query 2.Execute 3.Cast to List of objects 1.Create Query 2.Execute 3.Cast to List of objects test5.jsp

Retrieving a subset of entities based on a value <% PersistenceManager pm = PMF.getPMF().getPersistenceManager(); try { Query query = pm.newQuery(Test3Members.class, "department == :dd && coursenum >= :cn"); List allTest3 = (List )query.execute("CS", 400); for (Test3Members obj : allTest3) { out.write(" "+obj.getDepartment()+obj.getCoursenum()+": difficulty "+obj.getDifficulty()+" "); out.write(" "+obj.getDescription()+" "); out.write(" "); } query.closeAll(); } finally { pm.close(); } %> 1.Create Query with parameters 2.Bind parameter values on execute 3.Cast to List of objects 4.Close query when done 1.Create Query with parameters 2.Bind parameter values on execute 3.Cast to List of objects 4.Close query when done test5a.jsp

Retrieving an object by key <% PersistenceManager pm = PMF.getPMF().getPersistenceManager(); try { Query query = pm.newQuery(Test3Members.class); query.setOrdering("id desc"); List allTest3 = (List )query.execute(); long maxId = allTest3.get(0).getID(); Test3Members highest = pm.getObjectById(Test3Members.class, maxId); out.write(highest+"..."+highest.getID()); query.closeAll(); } finally { pm.close(); } %> 1.Use getObjectById to retrieve 2.If object might not exist, catch JDOObjectNotFoundException or JDOException 1.Use getObjectById to retrieve 2.If object might not exist, catch JDOObjectNotFoundException or JDOException test5b.jsp

Deleting entities test5c.jsp <% PersistenceManager pm = PMF.getPMF().getPersistenceManager(); try { Query query = pm.newQuery(Test3Members.class, "coursenum >= 600"); List toDelete = (List )(query.execute()); pm.deletePersistentAll(toDelete); query.closeAll(); } finally { pm.close(); } %> 1.Retrieve list of objects to delete (which seems inefficient?!?!) 2.Invoke pm.deletePersistentAll 1.Retrieve list of objects to delete (which seems inefficient?!?!) 2.Invoke pm.deletePersistentAll

By the way… Query has a closeAll() method. – close the query when you’re done with results Query has a deletePersistentAll() instance method. It is painfully slow in some SDKs. – If you use this method, be sure to assess how fast it is on very large sets of objects before you rely on it.

Now what if two people want to manipulate an object at the same time? public class private String title; private TreeSet categories = new TreeSet (); public void addCategory(Integer category) { categories.add(category); } <% String title = request.getParameter("title"); if (title == null) out.write("provide a title"); else { PersistenceManager pm = PMF.getPMF().getPersistenceManager(); try { Test1Object obj = null; try { obj = pm.getObjectById(Test1Object.class, title); } catch (JDOObjectNotFoundException doesNotExist) { obj = new Test1Object(); obj.setTitle(title); } obj.addCategory(Math.round(Math.rand()*100)); pm.makePersistent(obj); } finally { pm.close(); } %>

You need a transaction when your servlet needs to… Update an entity if it already exists, or create a new one otherwise Compute a new member variable value based on an existing value Modify multiple entities in a consistent way … Do anything where your servlet could potentially be confused if gets two simultaneous requests/hits from users

Setting up a simple transaction Transaction trans = pm.currentTransaction(); trans.begin(); Test1Object obj = null; try { obj = (Test1Object)pm.getObjectById(Test1Object.class, title); } catch (JDOObjectNotFoundException doesNotExist) { obj = new Test1Object(); obj.setTitle(title); } pm.makePersistent(obj); trans.commit(); 1.Tell the current transaction to begin tracking operations 2.Do your operations 3.Commit your changes 4.(On uncaught exception, changes are rolled back automatically) 1.Tell the current transaction to begin tracking operations 2.Do your operations 3.Commit your changes 4.(On uncaught exception, changes are rolled back automatically) test2.jsp

Transactions on GAE A transaction places an optimistic lock all of the entities in a certain group If any other transaction tries to modify entities in that group, then – The first transaction to commit is successful – The second (and later) transactions fail on commit In practice, contention can cause commits to fail… so just retry Very very similar to DBMS optimistic locking, which we all know and love, except for this concept of entity groups

Entity groups Groups partition the set of all entities in GAE Every entity is in exactly one group Every group has at least one entity Every group is very similar to tree – It has a root (which is used to identify the group) – Every entity has a parent (which for roots is the entity itself – this is where the tree analogy breaks) Overall, therefore, the datastore is a forest

In other words… A transaction can lock one, and only one, tree in the forest Oregon State CSECE CS361 CS496 Univ Oregon Info SysArt History IS434 IS210 Univ Calif Berkeley CSECE CS364 CS351 CS364

Entities in a group are stored in the same place(s) in distributed file system Remember: Your data values are copied (replicated) to many different servers. Storing entities that are locked together (a group) helps to improve performance Downside: an entity’s group cannot be changed after the entity is first saved Odd side-effect: entities are only affected by a transaction if they are retrieved by implicit specification of a file system location, e.g., retrieval by key or via a query that references an ancestor filter (e.g., parent key)

How to set up entity groups Option 1: Use JDO Relationships to specify that the child is dependent on the parent Option 2: Use custom JDO Key object that identifies the parent entity for a child entity

Option 1: Use JDO Relationships This is different than a compound object (an object that has multiple parts) It is when you have two entities, one of which is a child of another The parent “owns” the child in JDO-speak

Example code snippet public class = = "datanucleus", key = "gae.encoded-pk", value = "true") private String private HashSet employees = new HashSet (); = IdentityType.APPLICATION) public class = = "datanucleus", key = "gae.encoded-pk", value = "true") private String id;

Example servlet code Test3JDOEmployer boss = new Test3JDOEmployer(); boss.setName("Employer "+empname); for (int empid = 1; empid <= 3; empid++) { Test3JDOEmployee worker = new Test3JDOEmployee(); worker.setName("Employee "+empname); boss.addEmployee(worker); } pm.makePersistent(boss);

In the servlet… In the servlet – Just initialize and store the parent (no explicit child save) – On load, just load the parent and access child via the parent as needed FYI: Child objects are not loaded until they are read or written, so loading the parent can be faster.

Option 2: Use explicit JDO Keys Which I’m not going to show you in detail because it is much more hassle to set up, and it doesn’t really add any more benefits. But here’s how you can do it: – Only list the keys of the child in the parent – When instantiating the child, pass the parent’s key – In the child’s constructor, use KeyFactory to construct a child key, based on the parent’s key – See GAE Book for details (note typos)

Summary of important points Use a transaction if two simultaneous hits to the server could lead to inconsistency Each transaction can only operate on a single entity group – To put multiple entities in the same group, use a JDO parent-child relationship If you need a transaction and you need to modify multiple entity groups, use cursors and transactional tasks