Training - Day 3 OJB. What is OR Mapping? OR Mapping is the mapping of relational database tables to objects (Java Objects in our case) Many OR Mapping.

Slides:



Advertisements
Similar presentations
Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
Advertisements

Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
Day 3 - Basics of MySQL What is MySQL What is MySQL How to make basic tables How to make basic tables Simple MySQL commands. Simple MySQL commands.
MySQL-Database Teppo Räisänen Oulu University of Applied Sciences School of Business and Information Management.
Fundamentals, Design, and Implementation, 9/e Chapter 12 ODBC, OLE DB, ADO, and ASP.
JDBC CS-328. JDBC Java API for accessing RDBMS Allows use of SQL for RDBMS programming Can be used for: –embedded SQL –execution of stored queries.
1 JDBC Java Database Connectivity. 2 c.pdf
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
Fast Track to ColdFusion 9. Getting Started with ColdFusion Understanding Dynamic Web Pages ColdFusion Benchmark Introducing the ColdFusion Language Introducing.
Hash Tables1 Part E Hash Tables  
Introduction to Java Programming Language Junji Zhi University of Toronto 1.
SQLLite and Java CS-328 Dick Steflik. SQLLite Embedded RDBMS ACID Compliant Size – about 257 Kbytes Not a client/server architecture –Accessed via function.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
SQL Basics+ Brandon Checketts. Why SQL? Structured Query Language Structured Query Language Frees programmers from dealing with specifics of data persistence.
An Introduction to Hibernate Matt Secoske
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Data Persistence and Object-Relational Mapping Slides by James Brucker, used with his permission 1.
Web Application Development Muhammad Ali Versonic Pte Asher Imtiaz Forman Christian College.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Copyright © Curt Hill SQL The Data Definition Language.
Agenda What is Hibernate Spring Integration Questions Overview
IS-907 Java EE JPA: Simple Object-Relational Mapping.
Hive : A Petabyte Scale Data Warehouse Using Hadoop
Frank Hilhorst President Progressive Consulting Inc. Open Source Data Sharing.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 38 Advanced Java Database.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
CSC 2720 Building Web Applications Database and SQL.
SQL Data Definition Language (DDL) Using Microsoft SQL Server 1SDL Data Definition Language (DDL)
1 JDBC – Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
Chapter 18 Object Database Management Systems. McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. Outline Motivation for object.
Spring Database Access Ojitha Kumanayaka Copyright © Virtusa, 2007.
Hibernate Persistence. What is Persistence Persist data to database or other storage.  In OO world, persistence means persist object to external storage.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 33 Advanced Java.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
Chapter 8 Databases.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
Advanced Database CS-426 Week 1 - Introduction. Database Management System DBMS contains information about a particular enterprise Collection of interrelated.
MySQL More… 1. More on SQL In MySQL, the Information Schema is the “Catalog” in the SQL standard SQL has three components: Data definition Data manipulation.
Copyright Curt Hill Variables What are they? Why do we need them?
1 Active Records. 2 What’s Active Records? O-R Mapping layer To make database access almost a non-issue Relies heavily on convention over configuration.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
1 Nov 29, 2005 Object Relational Mapping Frameworks Wiene Höweler.
1 CS 430 Database Theory Winter 2005 Lecture 10: Introduction to SQL.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
1 CS 430 Database Theory Winter 2005 Lecture 11: SQL DDL.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
JDBC Part II CS 124. More about JDBC Types Statement versus PreparedStatement Timeout NULL values Meta-data close() methods Exceptions Transactions JDBC.
Relational Databases and MySQL. Relational Databases Relational databases model data by storing rows and columns in tables. The power of the relational.
Chapter 18 Object Database Management Systems. Outline Motivation for object database management Object-oriented principles Architectures for object database.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Fundamentals of MyBATIS
1 JDBC – Java Database Connectivity CS , Spring 2010.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
JDBC. Database is used to store data permanently. These days almost all Applications needs database to store its data persistently. Below are the most.
1 JDBC – Java Database Connectivity THETOPPERSWAY.COM.
DB Apps Introduction SoftUni Team Technical Trainers
JDBC – Java Database Connectivity
Data Definition and Data Types
MySQL-Database Jouni Juntunen Oulu University of Applied Sciences
A very brief introduction
How to connect natively?
Design and Implementation of Software for the Web
null, true, and false are also reserved.
JDBC – Java Database Connectivity
Intro to Relational Databases
Jeff Webb Maria Baron Chris Hundersmarck
Data Model.
Data.
JDBC II IS
Presentation transcript:

Training - Day 3 OJB

What is OR Mapping? OR Mapping is the mapping of relational database tables to objects (Java Objects in our case) Many OR Mapping tools available –Hibernate –iBatis –OJB UIS supports Apache OJB –Current version: 1.0.4

Apache OJB Open source project sponsored by the Apache Project Makes working with a database feel like working with an Java object model SQL is seldom used –OJB generates the SQL –Criteria objects

Some of the features… Store and retrieve Java objects to/from any JDBC compliant RDMS No special interfaces needed for your OJB objects – transparent persistence Object graphs can be persisted by persisting the root object Mapping support for 1:1, 1:n, and m:n associations OR Mappings defined in an XML repository Can use multiple databases Lazy loading via proxies (JDK or CGLIB) Support for polymorphism and extents Multiple sequence manager implementations Connection pooling and reuse of prepared statements JTA and JCA integration Optimistic (via number or timestamp) and pessimistic locking supported Support for object caching

Supported APIs Persistence Broker (PB) –Low level kernel API –Foundation of the others below ODMG –Object Data Management Group Persistence 3.0 –Full support JDO –Java Data Objects –Partial support OTM –Object Transaction Manager –API or tool to build other tools on –Specific to OJB

Persistence Broker Kuali supported API Low level API compared to OTM, ODMG or JDO, but still very easy to use Store, update, delete, and retrieve objects or collections of objects More on the PB after we learn how to configure OJB and map relationships

OJB.properties Usually found on the root of the project classpath When upgrading OJB from any version, this file should be replaced and updated Key points –Location of the repository.xml file –How to obtain database connections –How to obtain proxies –How to manage transactions

Example Let’s take a look at a real OJB.properties file

The Repository Mapping repository.xml usually on the root of the project classpath A DTD is also needed Good idea to break up the contents of repository.xml for easy reuse (testing) –repository_user.xml : OR Mappings –repository_database.xml : Database config

repository.xml <!DOCTYPE descriptor-repository PUBLIC "-//Apache Software Foundation//DTD OJB Repository//EN" "repository.dtd" [ ]> <descriptor-repository version="1.0" isolation-level="read-uncommitted" proxy-prefetching-limit="50"> &database; &user;

repository_database.xml <jdbc-connection-descriptor jcd-alias="MYDB" default-connection="true" platform="Oracle9i" jdbc-level="3.0" batch-mode="false" useAutoCommit="1" ignoreAutoCommitExceptions="false" testOnBorrow="true" testWhileIdle="true" testOnReturn="true" validationQuery="select 1 from dual">

Where you define your table to object mapping <class-descriptor class="edu.iu.uis.train.domain.User" table="TRN_USR_T">

A database column, or object property <field-descriptor name=”username" column=”usr_nm" jdbc-type="VARCHAR" />

A few special fields Primary keys –primarykey= “ true ” Auto-incrementing PK –autoincrement= “ true ” –Will use the Sequence Manager that you have configured –If using Oracle sequences, you can set the sequence name: sequence-name= “ some seq ” Locking field (we use optimistic locking – fast, data integrity only checked on an update) –locking= “ true ” –Need to store a hidden locking field on JSP pages –Long – incremented each time the column is updated Long is recommended because of Oracle Other possibilities are Integer and Timestamp

JDBC Types JDBC Type Java Type CHAR String VARCHAR String LONGVARCHAR String NUMERIC java.math.BigDecimal DECIMAL java.math.BigDecimal BIT boolean / Boolean BOOLEAN boolean / Boolean TINYINT Byte / byte SMALLINT Short / short INTEGER Integer / int BIGINT Long / long REAL Float / float FLOAT Double / double DOUBLE Double / double BINARY byte[] VARBINARY byte[] LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp CLOB Clob BLOB Blob ARRAY Array DISTINCT mapping of underlying type STRUCT Struct REF Ref DATALINK java.net.URL JAVA_OBJECT underlying Java class

1:1 Relationship <reference-descriptor name=”movie" class-ref="edu.iu.uis.train.domain.Movie" auto-retrieve="true" auto-update="false" auto-delete="false" > <foreignkey field-ref=”movieId" target-field-ref="movieId"/>

1:n Relationship or m:n Relationship <collection-descriptor name=”userCollection" element-class-ref="edu.iu.uis.train.domain.User" auto-retrieve="true" auto-update="true" auto-delete="true" proxy="false"> <inverse-foreignkey field-ref=”userId" target-field-ref=”userId"/>

repository_user.xml Let’s take a looks at this file in the exercises project

Exercise: Time to map your business objects Open repository_user.xml and complete the TODO items –Need DDL for columns and types –Need domain objects for attribute names (which are mapped to the columns)

Getting back to the PB API You can use the PB to: –Query –Insert and update –Delete It can also tap into database transactions, which you should probably do just about all, if not all, the time

Saving an object public static void storeProduct(Product product) { PersistenceBroker broker = null; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); broker.beginTransaction(); broker.store(product); broker.commitTransaction(); }catch(PersistenceBrokerException e) { if(broker != null) broker.abortTransaction(); // do more exception handling }finally { if (broker != null) broker.close(); }

Saving multiple objects public static void storeProducts(List products) { PersistenceBroker broker = null; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); broker.beginTransaction(); for (Object productObj : products) { Project product = (Product) productObj; broker.store(product); } broker.commitTransaction(); } catch(PersistenceBrokerException e) { if(broker != null) broker.abortTransaction(); // do more exception handling } finally { if (broker != null) broker.close(); }

Deleting an object public static void storeProduct(Product product) { PersistenceBroker broker = null; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); broker.beginTransaction(); broker.delete(product); broker.commitTransaction(); }catch(PersistenceBrokerException e){ if(broker != null) broker.abortTransaction(); // do more exception handling }finally { if (broker != null) broker.close(); }

Querying in OJB You can build up a template object and query You can use raw sql if you need to bypass OJB You can use a Criteria object –Recommended way –This is the only way I will demonstrate for now, but there’s great docs on the OJB website if you want to try something else

A simple query public static Collection getExpensiveLowStockProducts() { PersistenceBroker broker = null; Collection results = null; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); Criteria criteria = new Criteria(); criteria.addLessOrEqualThan("stock", new Integer(20)); criteria.addGreaterOrEqualThan("price", new Double( )); QueryByCriteria query = new QueryByCriteria(Product.class, criteria); results = broker.getCollectionByQuery(query); } finally { if (broker != null) broker.close(); } return results; }

More about the Criteria You can add just about any kind of “criteria” to build up an SQL statement Let’s take a look at the API

Updating an object public static boolean sellOneProduct(Integer stock) { PersistenceBroker broker = null; boolean isSold = false; try { broker = PersistenceBrokerFactory.defaultPersistenceBroker(); Criteria criteria = new Criteria(); criteria.addLessOrEqualThan("stock", stock); criteria.addGreaterOrEqualThan("price", new Double( )); QueryByCriteria query = new QueryByCriteria(Product.class, criteria); Product result = (Product) broker.getObjectByQuery(query); if (result != null) { broker.beginTransaction(); result.setStock(new Integer(result.getStock().intValue() - 1)); broker.store(result); broker.commitTransaction(); isSold = true; } } catch(PersistenceBrokerException e) { if(broker != null) broker.abortTransaction(); // do more exception handling } finally { if (broker != null) broker.close(); } return isSold; }

Exercise: The MovieDAOImpl It’s time to write your first DAO You shouldn’t need to extend any files, just implement the MovieDAO interface –Use eclipse to do this when you create the class and it will create all of the methods for you –Let’s do this part together

A better way to do all this Now that you’ve seen how the PB API works, there’s a much better way to work with OJB We will see more of this when we talk about Spring

References Object Relational Bridge – OJB Tutorials – mary.htmlhttp://db.apache.org/ojb/docu/tutorials/sum mary.html