Table of Content. Introduction to ObjectDB and JPA. Object Model: Types, Entities, Primary Keys. Database Connections



Similar documents
PERFORMANCE EVALUATION OF JAVA OBJECT-RELATIONAL MAPPING TOOLS HASEEB YOUSAF. (Under the Direction of John A. Miller)

Easy-Cassandra User Guide

Performance Evaluation of Java Object Relational Mapping Tools

Enterprise JavaBeans 3.1

OTN Developer Day Enterprise Java. Hands on Lab Manual JPA 2.0 and Object Relational Mapping Basics

Object Database Tutorial

Object Oriented Databases. OOAD Fall 2012 Arjun Gopalakrishna Bhavya Udayashankar

Object Oriented Database Management System for Decision Support System.

Spring Data, Jongo & Co. Java Persistenz-Frameworks für MongoDB

Lag Sucks! R.J. Lorimer Director of Platform Engineering Electrotank, Inc. Robert Greene Vice President of Technology Versant Corporation

Core Java+ J2EE+Struts+Hibernate+Spring

Develop an Asset Management System (AMS) for Ho Chi Minh University of Industry

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

Object-Oriented Databases Course Review

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

Introduction to Object-Oriented and Object-Relational Database Systems

Object-Oriented Databases db4o: Part 2

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Database Query 1: SQL Basics

Case Studies of Running the Platform. NetBeans UML Servlet JSP GlassFish EJB

Java Application Performance

Database Administration with MySQL

Hibernate Language Binding Guide For The Connection Cloud Using Java Persistence API (JAP)

MySQL for Beginners Ed 3

Firebird. Embedded SQL Guide for RM/Cobol

A Brief Introduction to MySQL

Object Oriented Design with UML and Java. PART XVIII: Database Technology

Object Relational Database Mapping. Alex Boughton Spring 2011

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

1 Introduction FrontBase is a high performance, scalable, SQL 92 compliant relational database server created in the for universal deployment.

rpaf KTl enterprise EJB 3.1 Cookbook I I flv* IV I I professional expertise distilled

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

Weaving Stored Procedures into Java at Zalando

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

White Paper: 1) Architecture Objectives: The primary objective of this architecture is to meet the. 2) Architecture Explanation

Object Oriented Databases (OODBs) Relational and OO data models. Advantages and Disadvantages of OO as compared with relational

Object-Oriented Query Languages: Object Query Language (OQL)

Resco CRM Server Guide. How to integrate Resco CRM with other back-end systems using web services

Enterprise Application Development In Java with AJAX and ORM

3 Techniques for Database Scalability with Hibernate. Geert Bevin - SpringOne 2009

ORM IN WEB PROGRAMMING. Course project report for 6WW Erik Wang

The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala , as well as the version history.

Java EE 7: Back-End Server Application Development

7. Excursus: Business Information Systems Darmstadt University of Applied Sciences, Department of Computer Science Dr. Markus Voß (Accso GmbH)

The ObjectStore Database System. Charles Lamb Gordon Landis Jack Orenstein Dan Weinreb Slides based on those by Clint Morgan

Information and Computer Science Department ICS 324 Database Systems Lab#11 SQL-Basic Query

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals NEW

OBJECTS AND DATABASES. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 21

Java EE Web Development Course Program

Customer Bank Account Management System Technical Specification Document

Web Development in Java

Course Number: IAC-SOFT-WDAD Web Design and Application Development

MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC

Accelerated Java EE Open Source Development with Eclipse CON1905

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Agile Development and Schema Evolution. Schema Evolution Agile Development & Databases Case Study on the Herschel Project

Facebook Twitter YouTube Google Plus Website

CREATING HIGH PERFORMANCE BIG DATA APPLICATIONS WITH THE JAVA PERSISTENCE API

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

Cocoon Field Day. Cocoon & Persistence

Using Apache Derby in the real world

Spring,2015. Apache Hive BY NATIA MAMAIASHVILI, LASHA AMASHUKELI & ALEKO CHAKHVASHVILI SUPERVAIZOR: PROF. NODAR MOMTSELIDZE

How graph databases started the multi-model revolution

Using Object Database db4o as Storage Provider in Voldemort

Oracle Database 12c: Introduction to SQL Ed 1.1

Using Relational Databases to Provide Object Persistence

Object Oriented Software Design

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Data Stream Management and Complex Event Processing in Esper. INF5100, Autumn 2010 Jarle Søberg

Data Mining Extensions (DMX) Reference

OBJECT PERSISTENCE AND AGILE SOFTWARE DEVELOPMENT

Cache Database: Introduction to a New Generation Database

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Research Article. ISSN (Print) *Corresponding author Lili Wang

F1: A Distributed SQL Database That Scales. Presentation by: Alex Degtiar (adegtiar@cmu.edu) /21/2013

Intro to Databases. ACM Webmonkeys 2011

Nicholas S. Williams. wrox. A Wiley Brand

Introduction to Java

Should we use Object Database Management Systems?

Amazon Redshift & Amazon DynamoDB Michael Hanisch, Amazon Web Services Erez Hadas-Sonnenschein, clipkit GmbH Witali Stohler, clipkit GmbH

Oracle Database: SQL and PL/SQL Fundamentals

CIS 631 Database Management Systems Sample Final Exam

Spring Data JDBC Extensions Reference Documentation

Object Database Management Systems (ODBMSs)

Rapid Application Development. and Application Generation Tools. Walter Knesel

Microsoft Access 3: Understanding and Creating Queries

Java (12 Weeks) Introduction to Java Programming Language

Developing an EJB3 Application. on WebSphere 6.1. using RAD 7.5

T-SQL STANDARD ELEMENTS

Java Interview Questions and Answers

Big Data Analytics in LinkedIn. Danielle Aring & William Merritt

L7_L10. MongoDB. Big Data and Analytics by Seema Acharya and Subhashini Chellappan Copyright 2015, WILEY INDIA PVT. LTD.

OUR COURSES 19 November All prices are per person in Swedish Krona. Solid Beans AB Kungsgatan Göteborg Sweden

How To Extend Content Broker Storage On Libs Libs (Libs) With Libs 4.5) And Libs 5.5

DIPLOMA IN WEBDEVELOPMENT

MongoDB Developer and Administrator Certification Course Agenda

Parameter Fields and Prompts. chapter

Transcription:

ObjectDB

Table of Content Introduction to ObjectDB and JPA Object Model: Types, Entities, Primary Keys. Database Connections JPA Fundamentals (CRUD Operations) Java Persistence Query Language (JPQL) JPA Query API and Criteria Query API References 2

Introduction

Object Relational Impedance Mismatch Application RDBMS? Database uses tables and records. Application uses classes and objects. Solutions: Application scope (ad hoc) transformations Object Relational Mapping (ORM) ODBMS (and other NoSQL Databases) 4

Object Relational Mapping (ORM) Application RDBMS ORM Moderate conservative solution (Adapter) for the Object Relational Mismatch problem. JDO, EJB, JPA, Hibernate, EclipseLink, OpenJPA, DataNucleus, Entity Framework, NHibernate. Simplifies development (solves many issues). Doesn't solve performance issues. 5

Object Oriented Databases (ODBMS) Application ODBMS No Object Relational Mismatch - application and database share the same class based schema. Very effective for complex data models. Standards: ODMG (and OQL), JDO. Versant, Objectivity/DB, GemStone, ObjectStore, InterSystems Cache, Matisse, db4o, ObjectDB. Small market share relative to RDBMS. 6

Performance (logarithmic scale) http://jpab.org/all/all/all.html 7

Performance (linear scale) http://jpab.org/all/all/all.html 8

ODBMS vs RDBMS vs Other NoSQL RDBMS + SQL (JDBC) RDBMS + ORM (JPA) ODBMS Most NoSQL Popularity Very High Very High Low Increasing Tools Many Many Few Few Independent Data Representation Very High Very High Low High Consistency ACID ACID ACID Limited Query Execution Rich, Fast Rich, Fast Rich, Fast (Varies) Limited Complex Models Complex, Slow Slow Fast Varies Object Oriented Integration Low High Very High Varies Scalability High High High Very High 9

ObjectDB Commercial, free for small databases (up to 10 classes, one million objects). History: 2003: version 1.0, JDO API. 2010: version 2.0, JPA, JDO APIs. Current version (2011) 2.3.2. Embedded and Client-Server modes. Tools: Explorer, Doctor, Enhancer, Replication, Online Backup, BIRT Driver. 10

ObjectDB Sample Users 11

ObjectDB Distribution 12

API Basics (JPA) import javax.persistence.*; Persistence EntityManagerFactory Interfaces EntityManager EntityTransaction Query Annotations Enums Exceptions @Entity @Embeddable FlushModeType PersistenceException @Id @GeneratedValues LockModeType TransactionRequiredException 13

Object Model (Types)

World Object Model @Entity public class Country { @Id String id; @Index String name; long population; double area; City capital; List<City> cities; Set<Country> neighbors; Map<String,Float> religions; List<String> languages; GDP gdp; Float unemployment;... } @Entity public class City { @Id @GeneratedValue long id; String name; long population; boolean capital;... } @Embeddable public class GDP { long total; int percapita;... } 15

World Database in the Explorer 16

Persistent State Entity & Embeddable Fields: Persistent Fields Transient Fields (transient, @Transient, final) Inverse (Mapped By) Fields Entity Fields: Primary Key Fields (@Id, @EmbeddedId) Version Field (@Version) Access Mode: Field / Property 17

Supported Types User Defined Entity and Embeddable classes Java Value Types: Primitives (int, float, ) Wrappers (Integer, Float, ) String, BigInteger, BigDecimal Date, Time, Timestamp, Calendar Enum types (system and user defined) Java Collections and Maps Any other serializable type 18

Primary Key Every entity object can be uniquely identified by type + primary key - e.g. in em.find(cls, pk). Primary Key Modes: Implicit Primary Key Single Field (@Id) Composite - Multiple Fields (@Id, @IdClass) Composite Embedded Id (@EmbeddedId) Most comparable value types are supported. Set by Application or by @GeneratedValue. 19

Composite Primary Key @Entity @IdClass(ProjectId.class) public class Project { @Id int departmentid; @Id long projectid;... } Class ProjectId { int departmentid; long projectid; } @Entity public class Project { @EmbeddedId ProjectId id;... } @Embeddable Class ProjectId { int departmentid; long projectid; } 20

Indexes Indexes are used in queries for: Retrieval (range / scan). Ordering results. MAX and MIN aggregate expressions. JDO Annotations for indexes: @Index, @Indices, @Unique, @Uniques. Supported Indexes: Single Field / Composite Indexed collections Multi Part Path Index 21

Schema Evolution Automatic Schema Evolution when: New field is added. Existing field is removed. Field type is modified. Class hierarchy is changed. Fields are moved in class hierarchy. Semi-automatic Schema Evolution when: Package is renamed. Class is renamed or moved. Field is renamed. 22

Database Connections

Connection Management Obtaining an EntityManager EntityManagerFactory emf = Persistence.createEntityManagerFactory( "$objectdb/db/world.odb"); EntityManager em = emf.getentitymanager(); Cleanup em.close(); emf.close(); 24

Connection URLs Embedded URLs: C:\db\world.odb db/world.odb $objectdb/db/world.odb objectdb:db/world.tmp Client Server URLs: objectdb://localhost/my/world.odb objectdb://localhost:6136/my/world.odb URL Parameters objectdb://localhost/world.odb;user=a;password=a objectdb:mydbfile.tmp;drop 25

persistence.xml <?xml version="1.0" encoding="utf-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="world-pu"> <provider>com.objectdb.jpa.provider</provider> <class>com.objectdb.world.country</class> <class>com.objectdb.world.border</class> <class>com.objectdb.world.city</class> <class>com.objectdb.world.coordinates</class> <class>com.objectdb.world.gdp</class> <properties> <property name="javax.persistence.jdbc.url" value="objectdb://localhost/world.odb"/> <property name="javax.persistence.jdbc.user" value="admin"/> <property name="javax.persistence.jdbc.password" value="admin"/> </properties> </persistence-unit> </persistence> 26

In Java EE (EJB) and Spring Java EE @Stateless public class MyEJB { // Injected database connection: @PersistenceContext private EntityManager em;... } Spring MVC @Component public class MyComponent { // Injected database connection: @PersistenceContext private EntityManager em;... } 27

CRUD Operations

Creating Entities em.gettransaction().begin(); Country country = new Country(); country.setid("br"); // A new unmanaged entity is constructed. em.persist(country); // The new entity object becomes managed. em.gettransaction().commit(); // Updates are committed to the database. 29

Retrieving Entities Retrieval by Id Country country = em.find(country.class, "br"); Retrieval by Query TypedQuery<Country> query = em.createquery("select c from Country c"); List<Country> results = query.getresultlist(); Retrieval by Navigation for (Country c : results) { System.out.println(c.getCapital().getName()); } 30

Updating Entities em.gettransaction().begin(); Country c = em.find(country.class, "br"); // A managed object is retrieved. c.setpopulation(192376496) // The managed object is updated. em.gettransaction().commit(); // Updates are committed to the database. Efficient change detection for enhanced classes. Snapshot comparison for non enhanced classes. 31

Deleting Entities em.gettransaction().begin(); Country c = em.find(country.class, "br"); // A managed object is retrieved. em.remove(c); // The object is marked as removed. em.gettransaction().commit(); // Updates are committed to the database. 32

Cascading and Fetch Types Operations are cascaded by annotating relationships: @OneToMany(cascade=CascadeType.ALL, fetch=fetchtype.eager) private List<City> cities; Relationship annotations: @OneToOne, @ManyToOne, @OneToMany, @ManyToMany. Cascading Types: ALL, PERSIST, REMOVE, REFRESH, DETACH, MERGE. Fetch Types: EAGER, LAZY. 33

Advanced Topics Lock Management: Optimistic, Pessimistic. Detach and Merge Lifecycle Events: @PrePersist, @PostPersist, @PostLoad @PreUpdate, @PostUpdate, @PreRemove, @PostRemove. Bidirectional Relationships L2 Cache Metamodel API Configuration 34

Queries (JPQL)

A Basic JPQL Query SELECT c FROM Country [AS] c FROM declares query identification variables (at least one) representing entity scopes. SELECT declares the results. SELECT and FROM are required. WHERE, GROUP BY, HAVING and ORDER BY are optional. Queries are case insensitive except names of entities, attributes and relationships. 36

JPQL Literals String literals are Unicode characters enclosed in single quotes (e.g. 'College'), where single quote itself is represented by two single quotes (e.g. 'College''s') Numeric literals follow the Java and SQL syntax (e.g. 100, 5.7) including optional type suffixes (e.g. 1.5F). enum literals follow the Java syntax, where class name must be specified. Boolean literals are TRUE and FALSE 37

Operators and Precedence Navigation (.) Arithmetic Operators +, - (unary) * (multiplication), / (division) + (addition), - (subtraction) Comparison Operators =, <, <=, >, >=, <>, [NOT] BETWEEN, [NOT] LIKE, [NOT] IN, IS [NOT] NULL, IS [NOT] EMPTY, [NOT] MEMBER [OF] Logical operators NOT, AND, OR 38

WHERE Basic String Expression SELECT c FROM Country c WHERE c.name = 'Brazil' Basic Numeric Expression SELECT c FROM Country c WHERE c.area > 1000000 Logical Operators SELECT c FROM Country c WHERE (NOT c.area > 1000000) OR (c.population >= 10000000 AND c.population <= 50000000) 39

Parameters Positional Parameters SELECT c FROM Country c WHERE c.area >?1 AND c.population <=?2 Named Parameters SELECT c FROM Country c WHERE c.area > :area AND c.population <= :population Same parameter can be used more than once in the query string. 40

Relationship Navigation SELECT c FROM Country c WHERE c.capital.name = 'Paris' SELECT c FROM Country c, JOIN c.cities city WHERE city.name = 'Paris' SELECT c FROM Country c, JOIN c.capital city WHERE city.name = 'Paris' SELECT c FROM Country c WHERE c.cities.name = 'Paris' 41

JOIN Operation Types Inner Join SELECT c, l FROM Country c [INNER] JOIN c.languages l Left Outer Join SELECT c, l FROM Country c LEFT [OUTER] JOIN c.languages l Fetch Join SELECT c FROM Country c LEFT [OUTER] JOIN FETCH c.languages 42

Comparison Expressions SELECT c FROM Country c WHERE c.area <= :minarea c.area BETWEEN :a1 AND :a2 c.population.size / c.area > :ratio c.name <> :name c.name LIKE '_raz%' 43

String Functions SELECT c FROM Country c WHERE CONCAT(c.name, "123") = 'Brazil123' LENGTH(c.name) = :length LOCATE(c.name, 'a') > 0 LOCATE(c.name, 'a', 2) > 0 LOWER(c.name) = :name UPPER(c.name) = :name SUBSTRING(c.name 3, 3) = 'azi' TRIM(c.name) = :name TRIM(LEADING 'B' FROM c.name) = 'razil' TRIM(TRAILING 'l' FROM c.name) = 'Brazi' 44

Other Functions SELECT c FROM Country c WHERE... MOD(c.population.size, 2) = 0 ABS(c.area) <= 1000000 SQRT(c.area) <= 1000 c.gdp.date > CURRENT_DATE (... CURRENT_TIME, CURRENT_TIMESTAMP) SIZE(c.languages) >= 3 45

Other Conditional Expressions SELECT c FROM Country c WHERE... c.capital IS [NOT] NULL c.languages IS [NOT] EMPTY :lang [NOT] MEMBER [OF] c.languages c.name IN ('France', 'Germany') 46

Selection and Projection SELECT c.name FROM Country c SELECT c.capital FROM Country c SELECT c.name, c.capital FROM Country c SELECT l FROM Country c JOIN c.languages l WHERE c.population > 10000000 SELECT DISTINCT l FROM Country c JOIN c.languages l WHERE c.population > 10000000 47

Constructor Expressions SELECT NEW results.nameandarea( c.name, c.area) FROM Country c public class NameAndArea { private String name; private int area; public NameAndArea(String n, int a) { name = n; area = a; } String getname() { return name; } int getarea() { return area; } } 48

ORDER BY SELECT c FROM Country c ORDER BY c.name ASC SELECT c FROM Country c ORDER BY c.capital.name DESC SELECT c FROM Country c ORDER BY c.name, c.capital.name 49

Aggregate Functions SELECT COUNT(c) FROM Country c => Long SELECT SUM(c.area) FROM Country c => Long, Double, BigInteger, BigDecimal, null SELECT AVG(c.area) FROM Country c => Double SELECT MAX(c.name) FROM Country c => String, Date or Numeric Type SELECT MIN(c.name) FROM Country c => String, Date or Numeric Type 50

GROUP BY / HAVING SELECT SUBSTRING(c.name, 1, 1), COUNT(c) FROM Country c GROUP BY SUBSTRING(c.name, 1, 1) SELECT SUBSTRING(c.name, 1, 1), COUNT(c) FROM Country c WHERE LENGTH(c.name) >= 3 GROUP BY SUBSTRING(c.name, 1, 1) HAVING COUNT(c) >= 5 ORDER BY SUBSTRING(c.name, 1, 1) 51

Update and Delete Queries UPDATE Country AS c SET c.name = TRIM(c.name) UPDATE Country SET name = TRIM(name) UPDATE Country SET name = TRIM(name) WHERE population > 1000 DELETE FROM Country AS c WHERE c.population > 1000 DELETE FROM Country WHERE population > 1000 52

The Query API

Static Query Execution @NamedQuery(name="findLarge", query = "SELECT c FROM Country c " + "WHERE c.area > :area") @NamedQueries( {@NamedQuery(...), @NamedQuery(...)}) List<Country> results = (List<Country>) em.createnamedquery("findlarge"). setparameter("area", 100000). getresultlist(); 54

Dynamic Query Execution String query = "SELECT c FROM Country c " + "WHERE c.area > :area AND " + "c.population <= :population"; List<Country> results = (List<Country>)em.createQuery(query). setparameter("area", 100000). setparameter("population", 1000000). getresultlist(); Country c = (Country)em.createQuery(query). setparameter("area", 100000). setparameter("population", 1000000). getsingleresult(); 55

Criteria Queries CriteriaBuilder cb = em.getcriteriabuilder(); CriteriaQuery<Country> q = cb.createquery(country.class); Root<Country> c = q.from(country.class); q.select(c); ParameterExpression<Integer> p = cb.parameter(integer.class); q.where(cb.le(c.get("population"), p)); 56

The Query API Query setflushmode( FlushModeType flushmode) // AUTO or COMMIT Query setfirstresult(int startpos) Query setmaxresults(int maxresult) Query sethint( String hintname, Object value) List getresultlist() Object getsingleresult() int executeupdate() 57

The Query API (cont) Query setparameter( String name, Object value) Query setparameter(string name, Calendar value, TemporalType temptype) Query setparameter(string name, Date value, TemporalType temptype) Query setparameter( int position, Object value) Query setparameter(int pos, Calendar value, TemporalType temptype) Query setparameter(int pos, Date value, TemporalType temptype) 58

References

References ObjectDB Website http://www.objectdb.com Tutorials http://www.objectdb.com/tutorial Manual http://www.objectdb.com/java/jpa Forum http://www.objectdb.com/database/forum 60