Object-Oriented Persistence Techniques Using OSS By: Josh Schendel.

61
Object-Oriented Object-Oriented Persistence Techniques Persistence Techniques Using OSS Using OSS By: Josh Schendel By: Josh Schendel

Transcript of Object-Oriented Persistence Techniques Using OSS By: Josh Schendel.

Object-Oriented Persistence Object-Oriented Persistence Techniques Using Techniques Using

OSSOSS

By: Josh SchendelBy: Josh Schendel

OverviewOverview

Understanding the ProblemUnderstanding the Problem Database RefresherDatabase Refresher Object-Oriented Persistence:Object-Oriented Persistence:

In .NETIn .NET In Java (Hibernate)In Java (Hibernate)

Understanding the ProblemUnderstanding the Problem

““Software exists to solve a problem!”Software exists to solve a problem!”

~Every SE professor at this school~Every SE professor at this schoolImage from plg.uwaterloo.ca/ ~migod/fun/

The Good Old DaysThe Good Old Days In the early days of programming:In the early days of programming:

Hardware presented limitationsHardware presented limitations Fewer clock cycles to solve the problemFewer clock cycles to solve the problem Make best use of RAM and other resourcesMake best use of RAM and other resources Efficiency was critical!Efficiency was critical!

Programming teams were smallerProgramming teams were smaller Many programs written by a single personMany programs written by a single person Maintenance generally consisted of bug-fixesMaintenance generally consisted of bug-fixes

Image from www.upss.com/menus.htm

Software Evolved…Software Evolved…

All these GOTO’s are hard to follow!All these GOTO’s are hard to follow! Structural programming presents a more Structural programming presents a more

understandable flow of logicunderstandable flow of logic This main() is too long!This main() is too long!

Functional programming allows code to be Functional programming allows code to be split up into smaller partssplit up into smaller parts

I want to reuse parts of this program!I want to reuse parts of this program! Object-oriented programming abstracts data Object-oriented programming abstracts data

and methods into highly reusable data and methods into highly reusable data structuresstructures

Transitioning to OO:Transitioning to OO:Why did it happen?Why did it happen?

Maintenance is a growing concernMaintenance is a growing concern Project groups are getting largerProject groups are getting larger Code not always maintained by original Code not always maintained by original

authorauthor Integrated, robust software in demandIntegrated, robust software in demand

Efficiency is good, but…Efficiency is good, but… Current hardware alleviates many efficiency Current hardware alleviates many efficiency

concernsconcerns ““Tricks” made in the interest of increased Tricks” made in the interest of increased

efficiency are often unintelligible and hinder efficiency are often unintelligible and hinder maintainabilitymaintainability

The PointThe Point

The evolution of software has stressed The evolution of software has stressed maintainability over efficiency by maintainability over efficiency by employing objectsemploying objects Not all attributes simple, can contain other Not all attributes simple, can contain other

objectsobjects PolymorphismPolymorphism The fastest programs are NOT object-The fastest programs are NOT object-

oriented!oriented!

The PointThe Point

The evolution of relational database The evolution of relational database software has stressed parallelization and software has stressed parallelization and scalability over object-oriented supportscalability over object-oriented support Transactional-based processing to allow Transactional-based processing to allow

multiprocessing without corruption of datamultiprocessing without corruption of data Many database packages charge based on Many database packages charge based on

multiprocessor utilizationsmultiprocessor utilizations Can only store SIMPLE data types!!Can only store SIMPLE data types!!

StringsStrings DatesDates IntegersIntegers ……

The ProblemThe Problem

Object-oriented programming solutionsObject-oriented programming solutions Efficiency-based database solutionsEfficiency-based database solutions

How can we How can we persistpersist our our complex, polymorphic complex, polymorphic objectsobjects in these in these relational relational database systems in a database systems in a maintainable, object-maintainable, object-oriented oriented fashion?fashion?

OverviewOverview

Understanding the ProblemUnderstanding the Problem Database RefresherDatabase Refresher Object-Oriented Persistence:Object-Oriented Persistence:

In .NETIn .NET In Java (Hibernate)In Java (Hibernate)

Umm… What’s Persistence?Umm… What’s Persistence?

3 types of data in an application3 types of data in an application1.1. TransientTransient

2.2. PersistentPersistent

3.3. DetachedDetached

Information from http://www.hibernate.org/hib_docs/v3/reference/en/html/objectstate.html

Transient DataTransient Data

• Does not need to be “saved” or Does not need to be “saved” or retained after program exitsretained after program exits

• Does not contribute significant Does not contribute significant amount of state to the objectamount of state to the object

• Often temporary or derived Often temporary or derived information, and often local to a information, and often local to a functionfunction

Persistent DataPersistent Data

• Needs to be “saved” or retained after Needs to be “saved” or retained after program exitsprogram exits

• Contributes a significant amount of Contributes a significant amount of state to the objectstate to the object

• Often all private class variable for a Often all private class variable for a data object contain persistent datadata object contain persistent data

• Persistent data used to reconstruct Persistent data used to reconstruct the saved object after it has been the saved object after it has been savedsaved

Detached DataDetached Data

• Data that was loaded from a Data that was loaded from a database but has since been database but has since been changed or copiedchanged or copied

• ““Out of synch” with the databaseOut of synch” with the database• Can create undesirable statesCan create undesirable states

K, What’s a Relational K, What’s a Relational Database?Database?

““A relational database is a collection A relational database is a collection of data items organized as a set of of data items organized as a set of formally-described tables from which formally-described tables from which data can be accessed or data can be accessed or reassembled in many different ways reassembled in many different ways without having to reorganize the without having to reorganize the database tables.”database tables.”~http://searchoracle.techtarget.com/sDefinition/0,,sid41_gci212885,00.html~http://searchoracle.techtarget.com/sDefinition/0,,sid41_gci212885,00.html

A Database Looks A Database Looks Like…Like…

Relational Database Relational Database StructureStructure

1.1. ServerServer: : A running instance of the A running instance of the database software. Each server has database software. Each server has multiplemultiple

2.2. Databases: Databases: Contain a set of isolated Contain a set of isolated stored procedures, functions, and multiplestored procedures, functions, and multiple

3.3. Tables:Tables: (next page) (next page)

Relational Database Relational Database StructureStructure

3.3. TableTable: : An entity that stores a set of data.An entity that stores a set of data.1.1. Columns: Columns: Each stores a single attribute, or field

2.2. Rows:Rows: Each row is a “record”, or an instance of data Each row is a “record”, or an instance of data in its corresponding tablein its corresponding table

Tables…Tables…

NormalizationNormalization

Not all information about a system Not all information about a system can be persisted in a single tablecan be persisted in a single table

Not all information about a system is Not all information about a system is unrelatedunrelated

Information is Information is normalizednormalized across across several tablesseveral tables

Related information is Related information is linkedlinked via via keyskeys

Relationships…Relationships…

Image from www.koffice.org/kexi/

Database TermsDatabase Terms

Connection String: Connection String: A string of characters that is A string of characters that is used in establishing a connection to a databaseused in establishing a connection to a database

SQL:SQL: “Structured Query Language”, a protocol used “Structured Query Language”, a protocol used to specify information desired from a databaseto specify information desired from a database

JoinJoin: A means of combining the contents of records : A means of combining the contents of records from different tables based on certain criteriafrom different tables based on certain criteria

Key:Key: A field or set of fields on a table for which the A field or set of fields on a table for which the table is constrained in such a way that no two records table is constrained in such a way that no two records can coexist in the table with the same valuescan coexist in the table with the same values

Terms from Hibernate in Action

Database TermsDatabase Terms

Record: Record: One row of a table or resultset.One row of a table or resultset.

Query: Query: An instance of a SQL statement that has An instance of a SQL statement that has been sent to a database to be performedbeen sent to a database to be performed

Resultset:Resultset: The results of a query. All desired fields The results of a query. All desired fields of all records that fit the criteria in the query are of all records that fit the criteria in the query are returnedreturned

SerializationSerialization: The conversion of an object into a : The conversion of an object into a meaningfully formatted string for which the object meaningfully formatted string for which the object could use to reload its state at the time of conversioncould use to reload its state at the time of conversion

Terms from Hibernate in Action

OverviewOverview

Understanding the ProblemUnderstanding the Problem Database RefresherDatabase Refresher Object-Oriented Persistence:Object-Oriented Persistence:

In .NETIn .NET In Java (Hibernate)In Java (Hibernate)

3-Tiered Development3-Tiered Development

Presentation LayerPresentation Layer GUIGUI

Business Logic LayerBusiness Logic Layer ““Policy” layerPolicy” layer Monkeys!Monkeys!

Data/Services LayerData/Services Layer Database interactionsDatabase interactions

*Focus is on making Data Layer as*Focus is on making Data Layer asobject-oriented as the rest of the systemobject-oriented as the rest of the system

Picture and terms from http://www.officewizard.com/books/clientserver/ClientServerComputing.htm

Challenges of an OO Data Challenges of an OO Data LayerLayer

NormalizationNormalization Tables are split up to reduce redundant dataTables are split up to reduce redundant data Challenges developer’s capacity to treat each Challenges developer’s capacity to treat each

table as an objecttable as an object CompositionComposition

Objects contain other objectsObjects contain other objects Contained objects must be stored in separate Contained objects must be stored in separate

tabletable InheritanceInheritance

Store inherited objects inStore inherited objects in1.1. Separate table?Separate table?2.2. Same table, separate table for additional attributes?Same table, separate table for additional attributes?3.3. Same table, make table include attributes for all Same table, make table include attributes for all

descendents?descendents?

Pre-.NET Database Pre-.NET Database InterfacingInterfacing

ADOADO ““ActiveX Data Objects”ActiveX Data Objects” Supplied with VB6 for classic ASP Supplied with VB6 for classic ASP

applicationsapplications Set of objects used in interfacing with a Set of objects used in interfacing with a

databasedatabase Link to database remained open while Link to database remained open while

iterating through the returned dataiterating through the returned data Implemented using DOMImplemented using DOM

Terms from http://www.vbwm.com/articles/2002/tcole/adonet1/

.NET Database Interfacing.NET Database Interfacing

ADO.NET heavily revamps traditional ADOADO.NET heavily revamps traditional ADO DisconnectedDisconnected

On a transaction a connection is opened, data is On a transaction a connection is opened, data is retrieved, and connection is automatically closedretrieved, and connection is automatically closed

Saves server and database resources!Saves server and database resources! Implemented using XMLImplemented using XML

VERY easy for ADO.NET objects to read XML or to VERY easy for ADO.NET objects to read XML or to serialize contents into XMLserialize contents into XML

Doesn’t assume “one size fits all”Doesn’t assume “one size fits all” DataReaderDataReader DataSetDataSet

Terms from http://www.vbwm.com/articles/2002/tcole/adonet1/

.NET Database Interfacing.NET Database Interfacing

DataReaderDataReader ““Lightweight and quick”Lightweight and quick” Should be used for “quick and easy” Should be used for “quick and easy”

database queriesdatabase queries Able to quickly and efficiently iterate Able to quickly and efficiently iterate

over a resultsetover a resultset Read-onlyRead-only Often used to bind datagridsOften used to bind datagrids

Terms from http://www.vbwm.com/articles/2002/tcole/adonet1/

.NET Database Interfacing.NET Database Interfacing

DataSetDataSet ““Heavyweight but powerful”Heavyweight but powerful” Each query places the resultset in a Each query places the resultset in a

“table” in the DataSet“table” in the DataSet Can join tables within the DataSetCan join tables within the DataSet Can “query” the DataSet directly to filter Can “query” the DataSet directly to filter

recordsrecords Quick and easy conversion to and from Quick and easy conversion to and from

XMLXML Great for XML parsing and persistence!Great for XML parsing and persistence!

Terms from http://www.vbwm.com/articles/2002/tcole/adonet1/

.NET Database Interfacing.NET Database Interfacing

DataAdapterDataAdapter Mediates connection between Mediates connection between

DataReader/DataSet and the databaseDataReader/DataSet and the database Stores important database informationStores important database information

Connection stringConnection string SQL query to be sentSQL query to be sent Name of stored procedure (to be discussed)Name of stored procedure (to be discussed) ParametersParameters

Terms from http://www.vbwm.com/articles/2002/tcole/adonet1/

Code!Code!

Code from from http://www.developer.com/net/vb/article.php/10926_1540311_7

Sub LoadCustomers() Dim myConnection As New OleDb.OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Program” _ “Files\Microsoft Visual”) Dim myDataAdapter As New OleDb.OleDbDataAdapter( _ "Select * from Customers", myConnection) Dim myDataSet As New DataSet() ' Fill DataSet with table, call it 'Customers' myDataAdapter.Fill(myDataSet, "Customers")  

' Display first CompanyName field of first row in Customers table MessageBox.Show(myDataSet.Tables("Customers").Rows(0)("CompanyName"))End Sub

But Josh Doesn’t Like ItBut Josh Doesn’t Like It

Code from from http://www.developer.com/net/vb/article.php/10926_1540311_7

Sub LoadCustomers() Dim myConnection As New OleDb.OleDbConnection( _ "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Program” _ “Files\Microsoft Visual”)

Connection StringConnection String Hard codedHard coded Connection Strings are volatileConnection Strings are volatile

Change when switch from development to production Change when switch from development to production databasesdatabases

Make private constant for the class?Make private constant for the class? Not good enough – Connection strings are generally Not good enough – Connection strings are generally

constant throughout a projectconstant throughout a project Will end up redefining the same constant in every classWill end up redefining the same constant in every class

Solution: Project-wide constantSolution: Project-wide constant

But Josh Doesn’t Like ItBut Josh Doesn’t Like It

Code from from http://www.developer.com/net/vb/article.php/10926_1540311_7

Sub LoadCustomers() Dim myConnection As New OleDb.OleDbConnection(CONSTANTS.CONN_STRING) Dim myDataAdapter As New OleDb.OleDbDataAdapter( _ "Select * from Customers", myConnection) Dim myDataSet As New DataSet() ' Fill DataSet with table, call it 'Customers' myDataAdapter.Fill(myDataSet, "Customers")  

' Display first CompanyName field of first row in Customers table MessageBox.Show(myDataSet.Tables("Customers").Rows(0)("CompanyName"))End Sub

Replaced hard-coded connection stringReplaced hard-coded connection string

But Josh Doesn’t Like ItBut Josh Doesn’t Like It

Code from from http://www.developer.com/net/vb/article.php/10926_1540311_7

Sub LoadCustomers() Dim myConnection As New OleDb.OleDbConnection(CONSTANTS.CONN_STRING) Dim myDataAdapter As New OleDb.OleDbDataAdapter( _ "Select * from Customers", myConnection)

Query mixed in with the code!Query mixed in with the code! Modern databases offer stored procedures to Modern databases offer stored procedures to

aid in partitioning the Data Layeraid in partitioning the Data Layer Stored procedures offer many advantages Stored procedures offer many advantages

over formulating a query in-codeover formulating a query in-code

Stored ProceduresStored Procedures

Set of pre-written SQL statements Set of pre-written SQL statements that reside in the databasethat reside in the database

Code Code referencesreferences the stored the stored procedure instead of procedure instead of buildingbuilding the the SQL statementSQL statement

AdvantagesAdvantages1.1. CompilationCompilation

2.2. MaintainabilityMaintainabilityTerms from http://www.vbwm.com/articles/2002/tcole/adonet1/

Stored ProceduresStored Procedures

CompilationCompilation ““Compilation” of stored procedures does NOT Compilation” of stored procedures does NOT

produce byte code!produce byte code! Syntax checking done when saving the stored Syntax checking done when saving the stored

procedureprocedure You will not be allowed to save a stored You will not be allowed to save a stored

procedure that does not compileprocedure that does not compile Catch query errors at “compile” time rather than run Catch query errors at “compile” time rather than run

time!time! Bonus! Compilation allows speeds up queriesBonus! Compilation allows speeds up queries

Stored ProceduresStored Procedures

MaintainabilityMaintainability Stored procedures can be reused Stored procedures can be reused

throughout an applicationthroughout an application If the database changes, only need to update If the database changes, only need to update

each affected query once in the stored procedureeach affected query once in the stored procedure Readability enhancedReadability enhanced

Syntax highlightingSyntax highlighting Don’t need to escape as many characters since Don’t need to escape as many characters since

the procedure does not need to be encased in a the procedure does not need to be encased in a stringstring

Stored ProceduresStored Procedures

But Josh Doesn’t Like ItBut Josh Doesn’t Like It

Code from from http://www.developer.com/net/vb/article.php/10926_1540311_7

Sub LoadCustomers() Dim myConnection As New OleDb.OleDbConnection(CONSTANTS.CONN_STRING) Dim myDataAdapter As New OleDb.OleDbDataAdapter( _ “GET_CUSTOMERS” myConnection) myDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure; Dim myDataSet As New DataSet() ' Fill DataSet with table, call it 'Customers' myDataAdapter.Fill(myDataSet, "Customers")  

' Display first CompanyName field of first row in Customers table MessageBox.Show(myDataSet.Tables("Customers").Rows(0)("CompanyName"))End Sub

Replaced SQL with stored procedureReplaced SQL with stored procedure

But Josh Doesn’t Like ItBut Josh Doesn’t Like It

Code from from http://www.developer.com/net/vb/article.php/10926_1540311_7

This code is reusable and non-OOThis code is reusable and non-OO Developers care about Developers care about objectsobjects, not records in a , not records in a

DataSet!DataSet! Instead of repeating the code every time we Instead of repeating the code every time we

want the customers in the database, let’s make a want the customers in the database, let’s make a function that returns the resultset as objects of function that returns the resultset as objects of the expected typethe expected type

Dim myConnection As New OleDb.OleDbConnection(CONSTANTS.CONN_STRING) Dim myDataAdapter As New OleDb.OleDbDataAdapter( _ “GET_CUSTOMERS” myConnection) myDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure; Dim myDataSet As New DataSet() ' Fill DataSet with table, call it 'Customers' myDataAdapter.Fill(myDataSet, "Customers")  

But Josh Doesn’t Like ItBut Josh Doesn’t Like It

Code from from http://www.developer.com/net/vb/article.php/10926_1540311_7

This code is reusable and non-OOThis code is reusable and non-OO Developers care about Developers care about objectsobjects, not records in a , not records in a

DataSet!DataSet! Instead of repeating the code every time we Instead of repeating the code every time we

want the customers in the database, let’s make a want the customers in the database, let’s make a function that returns the resultset as objects of function that returns the resultset as objects of the expected typethe expected type

Function getCustomer(ByVal id As Integer) As Customer Dim myConnection As New OleDb.OleDbConnection(CONSTANTS.CONN_STRING) Dim myDataAdapter As New OleDb.OleDbDataAdapter( _ “GET_CUSTOMER” myConnection) myDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure; myDataAdapter.Parameters.Add(“@id”, id) Dim myDataSet As New DataSet() ' Fill DataSet with table, call it 'Customers' myDataAdapter.Fill(myDataSet, "Customers")   String CompanyName = myDataSet.Tables(“Customers”) _ .Rows(0).Item(“CompanyName”) … Customer customer = new Customer (CompanyName, …) Return customerEnd Function

Object-Oriented Persistence Object-Oriented Persistence in .NETin .NET

.NET offers powerful ADO.NET objects.NET offers powerful ADO.NET objects By defining constants, employing By defining constants, employing

stored procedures, and isolating Data stored procedures, and isolating Data Layer operations into object-oriented Layer operations into object-oriented functions, we can emulate an object-functions, we can emulate an object-oriented database from a relational oriented database from a relational oneone

OverviewOverview

Understanding the ProblemUnderstanding the Problem Database RefresherDatabase Refresher Object-Oriented Persistence:Object-Oriented Persistence:

In .NETIn .NET In Java (Hibernate)In Java (Hibernate)

Java PersistenceJava Persistence

Wouldn’t it be great if all you had to Wouldn’t it be great if all you had to do to save an object to the database do to save an object to the database was saywas say

session.save(customer);

Introducing Hibernate!Introducing Hibernate!

HibernateHibernate Open-source frameworkOpen-source framework Sits between “Policy” and “Data” layerSits between “Policy” and “Data” layer Transforms the frontend of a relational Transforms the frontend of a relational

database into an object-oriented database into an object-oriented databasedatabase

Information from Professional Hibernate

How Does it Work?How Does it Work?

InstallationInstallation JAR file with classpathJAR file with classpath

Supporting filesSupporting files hibernate.propertieshibernate.properties hibernate.cfg.xmlhibernate.cfg.xml

Information from Professional Hibernate

How Does it Work?How Does it Work?

hibernate.propertieshibernate.properties Non-XML formatNon-XML format Discrepancies between this and Discrepancies between this and

hibernate.cfg.xml lose out in favor of hibernate.cfg.xml lose out in favor of hibernate.cfg.xmlhibernate.cfg.xml

Will likely be depracated in the near futureWill likely be depracated in the near future

Information from Professional Hibernate

How Does it Work?How Does it Work?

hibernate.cfg.xmlhibernate.cfg.xml XML formatXML format Contains all the information needed to run Contains all the information needed to run

HibernateHibernate This includes:This includes:

Connection String / JDBC driver informationConnection String / JDBC driver information Need only be in ONE place in the project!Need only be in ONE place in the project!

Database dialect and other settingsDatabase dialect and other settings Class-to-table mappings or locations to class-to-Class-to-table mappings or locations to class-to-

table mapping filestable mapping files

Information from Professional Hibernate

How Does it Work?How Does it Work?

Database dialectDatabase dialect DialectDialect: A form of SQL that is constrained or : A form of SQL that is constrained or

contains proprietary keywords or formats contains proprietary keywords or formats that are specific to certain databasesthat are specific to certain databases

Since Hibernate takes care of much of the Since Hibernate takes care of much of the SQL, it must know correct dialect for the SQL, it must know correct dialect for the databasedatabase

Information from Professional Hibernate

How Does it Work?How Does it Work?

Class-to-table mappingsClass-to-table mappings Tells Hibernate what classes to persist, what Tells Hibernate what classes to persist, what

types each field is, and where all the types each field is, and where all the information should be persisted.information should be persisted.

Tells Hibernate how to generate IDsTells Hibernate how to generate IDs Provide FREE DOCUMENTATION on how the Provide FREE DOCUMENTATION on how the

relationship between relationship between object-orientedobject-oriented data in data in the application and the the application and the corresponding datacorresponding data in the database!in the database!

Information from Professional Hibernate

ExampleExample<hibernate-configuration>

<!-- a SessionFactory instance listed as /jndi/name --> <session-factory name="java:hibernate/SessionFactory">

<!-- properties --> <property name="connection.datasource">java:/comp/env/jdbc/MyDB</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">false</property> <property name="transaction.factory_class"> org.hibernate.transaction.JTATransactionFactory </property> <property name="jta.UserTransaction">java:comp/UserTransaction</property>

<!-- mapping files --> <mapping resource="org/hibernate/auction/Item.hbm.xml"/> <mapping resource="org/hibernate/auction/Bid.hbm.xml"/>

<!-- cache settings --> <class-cache class="org.hibernate.auction.Item" usage="read-write"/> <class-cache class="org.hibernate.auction.Bid" usage="read-only"/> <collection-cache collection="org.hibernate.auction.Item.bids" usage="read-write"/>

</session-factory>

</hibernate-configuration>

Hibernate and SQLHibernate and SQL

HQL (Hybernate Query Language)HQL (Hybernate Query Language) Hibernate offers a simplified query language Hibernate offers a simplified query language Very similar to traditional SQLVery similar to traditional SQL Uses dialects to convert the HQL into Uses dialects to convert the HQL into

appropriate SQLappropriate SQL SQLSQL

Hibernate also allows straight SQL Hibernate also allows straight SQL statements to be executedstatements to be executed

Good for optimizing queries that Hibernate Good for optimizing queries that Hibernate doesn’t compile efficientlydoesn’t compile efficiently

Information from Professional Hibernate

SessionsSessions

Each time a database interaction is Each time a database interaction is required, a required, a sessionsession must be used. must be used.

Sessions created from the Singleton Sessions created from the Singleton SessionFactorySessionFactory class class

Types of Database InteractionsTypes of Database Interactions1.1. SelectSelect2.2. LoadLoad3.3. InsertInsert4.4. UpdateUpdate5.5. DeleteDelete

Information from Professional Hibernate

SelectSelect

What is it?What is it? Query that creates a resultset that Query that creates a resultset that

contains the specified columns for all contains the specified columns for all records that meet a criteriarecords that meet a criteria

How does Hibernate make it easy?How does Hibernate make it easy?

Information from Professional Hibernate

try { Session session = sessionFactory.openSession(); List users = session.find(“from Users”); // HQL session.close(); } catch (Exception e) { }

LoadLoad

What is it?What is it? Query that retrieves a unique record Query that retrieves a unique record

from a table that has the same IDfrom a table that has the same ID How does Hibernate make it easy?How does Hibernate make it easy?

Information from Professional Hibernate

// ID initialized elsewhere try { User myUser = new User(); // blank Session session = sessionFactory.openSession(); List users = session.load(myUser, ID); // HQL session.close(); } catch (Exception e) { }

InsertInsert

What is it?What is it? Query that adds a new record to a Query that adds a new record to a

table with specified propertiestable with specified properties How does Hibernate make it easy?How does Hibernate make it easy?

Information from Professional Hibernate

User myUser = new User(“Josh”, “Schendel”, “schendej”); try { Session session = sessionFactory.openSession(); session.save(“myUser”); // HQL session.close(); } catch (Exception e) { }

UpdateUpdate

What is it?What is it? Query that changes the record in the Query that changes the record in the

database that has same ID as the database that has same ID as the objectobject

How does Hibernate make it easy?How does Hibernate make it easy?

Information from Professional Hibernate

//User loaded from database myUser.setName(“Mark”); try { Session session = sessionFactory.openSession(); session.update(“myUser”); // HQL session.close(); } catch (Exception e) { }

DeleteDelete

What is it?What is it? Query that removes a record that has Query that removes a record that has

the same ID from the databasethe same ID from the database How does Hibernate make it easy?How does Hibernate make it easy?

Information from Professional Hibernate

//User loaded from database try { Session session = sessionFactory.openSession(); session.delete(“myUser”); // HQL session.close(); } catch (Exception e) { }

Final Notes About HibernateFinal Notes About Hibernate

Simplifies object persistence Simplifies object persistence dramaticallydramatically Supports more complicated queriesSupports more complicated queries

Mapping documentsMapping documents Written onceWritten once Used everywhere to simplify persistenceUsed everywhere to simplify persistence

Fully support all joins and most SQL transactions Fully support all joins and most SQL transactions via dialectsvia dialects

Object-oriented interface to the database Object-oriented interface to the database without the cost of an object-oriented without the cost of an object-oriented databasedatabase

Information from Professional Hibernate

BibliographyBibliography

Pugh, Eric, and Gradecki, Joseph. Professional Hibernate. Wiley Publishing. 2004

Iverson, Will. Hibernate, a J2EE Developer’s Guide. Pearson. 2005

Minter, Dave, and Linwood, Jeff. Pro Hibernate 3. Wiley Publishing. 2005

Bauer, Christian, and King, Gavin. Hibernate in Action. Manning Publishing. 2005

HIBERNATE - Relational Persistence for Idiomatic Java. 3.11. 2/23/06. <http://www.hibernate.org/hib_docs/v3/reference/en/html/objectstate.html>Visual Basic Web Magazine. Cole, Tom. 2/23/06. <http://www.vbwm.com/articles/2002/tcole/adonet1/>