690 likes | 1.28k Views
Persistence in Java. What is persistence?. Object persistence means that individual objects can outlive the process that created it They can be saved to a data store and be re-created at the later point in time
E N D
What is persistence? • Object persistence means that individual objects can outlive the process that created it • They can be saved to a data store and be re-created at the later point in time • Persistence is one of the fundamental concepts in application development • Persistence in Java normally means storing data in a relational database using SQL
Persistence in applications • The approach to managing persistent data is a key design decision in almost every software project • As application developers we are more interested in implementing business logic, not in low-level data access coding • Java provides an API for database access and also several frameworks exist in this area
Layered architecture • A typical, proven, high-level application architecture uses three layers: • A persistence layer is the basis in a layered architecture
Java Database Connectivity Hibernate JDBC ORM implementation Persistence solutions Java Persistence API Java application SQL-based relational database
The role of SQL • To work with database effectively, a solid understanding of the relational model and SQL is a prerequisite • Strictly, a relational database is a collection of tables • SQL (Structured Query Language) is a language designed for the definition, retrieval and management of data in RDBMS
SQL overview [1/2] • Data definition language (DDL) to create a database schema with CREATE and ALTER • Data manipulation language (DML) to execute operations that manipulate and retrieve data • Data manipulation: • insertion • update • deletion
SQL overview [2/2] • Data can be retrieved by executing queries with • restriction • projection • join • For efficient reporting you can group, order and aggregate data in arbitrary ways • Nested statements - subselecting
Question – what’s the difference? • INNER JOIN • LEFT OUTER JOIN • RIGHT OUTER JOIN Will select all rows from both tables as long as there is a match between the columns we are matching on Selects all the rows from the first table listed after the FROM clause, no matter if they have matches in the second table Behaves exactly as LEFT JOIN, except that it returns all rows from the second table
Exercise ARTIST ALBUM ? SELECT artist.name, album.title FROM album INNER JOIN artist ON album.artist_id = artist.id; ? SELECT artist.name, album.title FROM album LEFT OUTER JOIN artist ON album.artist_id = artist.id; ? SELECT artist.name, album.title FROM album RIGHT OUTER JOIN artist ON album.artist_id = artist.id;
Answers SELECT artist.name, album.title FROM album INNER JOIN artist ON album.artist_id = artist.id; SELECT artist.name, album.title FROM album LEFT OUTER JOIN artist ON album.artist_id = artist.id; SELECT artist.name, album.title FROM album RIGHT OUTER JOIN artist ON album.artist_id = artist.id;
Using SQL in Java When you work with SQL database in a Java application, the Java code issues SQL statements to the database via the Java DataBase ConnectivityAPI
JDBC Java Database Connectivity
About JDBC • JDBC is an API for the Java programming language that defines how a client may access a database • JDBC has been part of the Java Standard Edition since the release of JDK 1.1 • The JDBC classes are contained in the Java package java.sql
Definition from Sun • JDBC API is the industry standard for database-independent connectivity between the Java programming language and a wide range of databases • relational databases • spreadsheets • flat files • "Write Once, Run Anywhere" capabilities for applications that require access to enterprise data
JDBC API Overview • The JDBC API makes it possible to do three things: • Establish a connection with a database or access any tabular data source • Send SQL statements • Process the results
Two JDBC components • The JDBC API contains two major sets of interfaces: • JDBC API for application writers • lower-level JDBC driver API for driver writers http://www.minq.se/products/dbvis/doc/main/doc/ug/getConnected/getConnected.html
JDBC drivers • JDBC allows multiple implementations (drivers) to exist and be used by the same application • To use JDBC you will need to install a driver on your machine • A JDBC driver can come from many sources, e.g. database software or a JDBC driver vendor
MySQL JDBC driver • The official JDBC driver for MySQL: • MySQL Connector/J • Web page: • http://dev.mysql.com/downloads/connector/j/5.1.html • Maven dependency configuration: <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency>
JDBC steps • Import JDBC packages import java.sql.Connection; import java.sql.SQLException; or import java.sql.*; • Open a connection to a database • Create a Statement object • Execute a SQL query • Process the ResultSet • Close the resources
Establishing a Connection • Typically, a JDBC application connects to a target data source using one of two mechanisms: • DriverManager • DataSource (preferable) • Establishing a connection (java.sql.Connection) involves two steps: • loading the driver • making the connection Class.forName("com.mysql.jdbc.Driver");
Connecting withDriverManager Connection conn = DriverManager .getConnection(URL, username, passwd); OR Connection conn = DriverManager.getConnection(URL); For example: Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost/music", "musicuser", "musicpassword");
Connecting withDataSource Increases application portability by making it possible to use a logical name for a data source instead of having to supply information specific to a particular driver InitialContext ic = new InitialContext() DataSource ds = ic.lookup("java:comp/env/jdbc/myDB"); Connection con = ds.getConnection(); DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource() ds.setPort(1527); ds.setHost("localhost"); ds.setUser("APP") ds.setPassword("APP"); Connection con = ds.getConnection();
Creating a SQL statement • First, instantiate an object that run the query against the database to which it is connected • This is done by the createStatement() method of the conn Connection object created before • A call to this method creates an object instance of the Statementclass Statement sql_stmt = conn.createStatement();
Executing a Query • Next, execute a query and obtain a ResultSet • This is done by using the executeQuery() method of the Statement object • A call to this method takes as parameter a SQL SELECT statement and returns a JDBC ResultSet object ResultSet rs = sql_stmt.executeQuery( "SELECT COF_NAME, PRICE FROM COFFEES");
Processing the ResultSet • Once the query has been executed, there are two steps to be carried out: • Processing the output ResultSet to fetch the rows next() method of the ResultSet object • Retrieving the column values of the current row getXXX() methods of the ResultSet object • Here getXXX() corresponds to the getInt(), getString() etc
Example Statement sql_stmt = conn.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = sql_stmt.executeQuery( "SELECT COF_NAME, PRICE FROM COFFEES"); while (rs.next()) { String name = rs.getString("COF_NAME"); float price = rs.getFloat("PRICE"); System.out.println(name + " " + price); }
Closing the ResultSet and Statement • Once the ResultSet and Statement objects have been used, they must be closed explicitly • This is done by calls to the close() method of the ResultSet and Statement classes • If not closed explicitly, there are two disadvantages: • Memory leaks can occur • Maximum Open cursors can be exceeded rs.close(); sql_stmt.close();
Closing the Connection • The last step is to close the database connection • This is done by a call to the close() method of the Connection class conn.close();
Exception handling • All operations throw checked exception java.sql.SQLException • Developer is required to catch and handle this exception each time
JDBC 4.0 Enhancements The major features added in JDBC 4.0 include: • Auto-loading of JDBC driver class • Connection management enhancements • Support for RowId SQL type • DataSet implementation of SQL using Annotations • SQL exception handling enhancements • SQL XML support JDBC 4.0 is a part of Java SE 6
ORM Object/relational mapping
Persistence in object-oriented applications • In an object-oriented application, persistence allows an object to outlive the process that created it • Application isn’t limited to single objects – entire graphs of interconnected objects may be made persistent and later re-created in a new process • Now we are interested in a mapping from domain object model to database tables
Example: object-relational mapping Java Application Database ??? Java Class Diagram ER Diagram
The paradigm mismatch • There is the mismatch between object-oriented paradigm and relational paradigm ! • The object-relational impedance mismatch is a set of conceptual and technical difficulties which are often encountered when a RDBMS is being used by a program written in an object-oriented programming language
First example • Projection and join SQL operations always result in a tabular representation of the resulting data • This is quite different than the graph of interconnected objects!
The problem of subtypes • SQL provides no direct support for inheritance • We can’t write a statement like CREATE TABLE CREDIT_CARD EXTENDS BILLING_DETAILS • Polymorphic associations and queries • Standard foreign key constraints refers to exactly one table
Solution for inheritance There are three different approaches to representing an inheritance hierarchy: • Table per concrete class - Discard polymorphism and inheritance relationshipscompletely from the relational model • Table per class hierarchy - Enable polymorphism by denormalizing the relationalmodel and using a type discriminator column to hold type information • Table per subclass - Represent “is a” (inheritance) relationships as “has a”(foreign key) relationships
The problem with identity • This problem can be seen when we consider two objects and check if they are identical • There are three ways to tackle it • Java world • Object identity (memory location, checked with a==b) • Equality as determined by equals() • Database world • Identity is expressed as the primary key value • As expected, they work together only with some help
The problem with identity • Neither equals() nor == is naturally equivalent to the primary key value • It’s common for several (non-identical) objects to simultaneously represent the same row of the database • It is recommended to use surrogate (system-generated) key wherever possible
Problems relating to associations Association mapping and the management of entity associations are central concepts of any object persistence solution • OO languages represent associations using object references and collections of object references • Relational world – foreign key column, with copies of key values in several tables
Problems relating to associations • Object references are inherently directional • Foreign key associations aren’t by nature directional. Navigation has no meaning for a relational data model. • Java associations may be many-to-many • Table associations are always one-to-many or one-to-one • Link tableis required for many-to-many in database
Problem of object graph navigation • There is a fundamental difference in the way to access objects in Java and in a relational database • Walking the object graph – navigate from one object to another, following associations between instances • Efficient access to relational data usually requires to use of joins between tables of interest • This is perhaps the single most common source of performance problems in Java applications aUser.getBillingDetails().getAccountNumber()
The cost of the mismatch • The overall solution for the list of mismatch problems can require a significant effort • The main purpose of up to 30% of the application code written is to handle the SQL/JDBC and the manual bridging of the ORM paradigm mismatch
Alternatives • Hard-coding a persistence layer with SQL/JDBC • Data Access Object pattern • Serialization • EJB entity beans • Object-oriented database systems • XML
ORM frameworks "An ORM implementation is a complex beast - less complex than an application server, but more complex than a web application framework like Struts or Tapestry", Hibernate in Action • Hibernate • TopLink (Oracle) EclipseLink • iBatis • OpenJPA (Apache)
References • Christian Bauer and Gavin King “Hibernate in Action”, Manning, 2004 • Java SE Technologies - Database http://java.sun.com/javase/technologies/database/ • JDBC Overview from Sun http://java.sun.com/products/jdbc/overview.html • JDBC 4.0 Enhancements in Java SE 6 http://www.onjava.com/pub/a/onjava/2006/08/02/jjdbc-4-enhancements-in-java-se-6.html
References • HSQLDB - Lightweight 100% Java SQL Database Engine http://hsqldb.org/