Hibernate Framework
An ORM Tool
Hibernate Implementation Workshop
Who should Attend
Knowledge of SQL (Oracle / MySQL) Java developers who need to explore alternative methods of persistence in Java applications.
Saving data to a storage is called persistence.
Programming with JDBC
Environment Required
Oracle 10g XE / MySQL Java Development Environment (JDK 5 or above) Hibernate Framework Libraries NetBeans 6 or above an IDE
Registration Case Study
To demonstrate the different steps involved in a Hibernate application We will develop an application that can add, update, delete or search a user in the database. As discussed, we can use Oracle database for storing the user information.
Setting up Database
Oracle 10g XE is a free Relational Database Management System based on the Structured Query Language (SQL). It is very fast reliable and flexible Database Management System based on relation model that is developed to manage large volumes of data at very high speed with security. Oracle 10g XE can be used for variety of applications but it is one of the most popular RDBMS used for the web applications on the Internet. Install Oracle 10g XE Database
You can go to http://www.oracle.com/ and download and install.
Setting Up Database Contd..,
Create an User “cec” with password “cec” We’ll use a single table ‘users’ to store the user information with the following fields. The syntax for the oracle is given below.
CREATE TABLE USERS( USER_ID NUMBER PRIMARY KEY, FIRST_NAME VARCHAR2(20), LAST_NAME VARCHAR2(20), AGE NUMBER, EMAIL VARCHAR(40) );
Working with IDE
NetBeans
is an open-source integrated development environment written entirely in Java. NetBeans IDE supports development of all Java application types (Java SE, web, EJB and mobile applications). Download from http://java.sun.com
Creating a Project Understanding Directory Structure Compiling Running a Project
Persistence in OO Applications
When an application is developed, a major portion of that application involves the creation and maintenance of the data to store and retrieve from the database. Persistence: The ability of an object to remain in existence past the lifetime of the program that creates it. The state of an object can be stored to a disc, and an object with the same state can be re-created at some point in future.
Persistence Implementation There are various ways the persistence layer can be implemented: Hard-coding with SQL/JDBC (more development and maintenance efforts are required) XML Persistence (just another text file; no capabilities for DB mgt. ) Using Object Serialization Other Solutions iBATIS, JDO, TopLink EJB 2.1 Entity Beans. EJB 3 with JPA
Programming with JDBC
We create a project “WorkShop” in NetBeans and add the Oracle JDBC driver to its Java build path. The location of that driver is cmd>{OracleXE_INSTALL_DIR}\app\oracle\product \10.2.0\server\jdbc\lib\ojdbc14.jar.
JDBC Initialization and Cleanup
Load the Driver Class.forName("oracle.jdbc.OracleDriver"); Establish a connection DriverManager.getConnection("jdbc:oracle: thin:@localhost:1521:XE","cec","cec"); Close the connection con.close();
Programming with JDBC contd..,
Using JDBC to add a record in USERS table Use SQL statement in the respective statement object of connection object. connection.prepareStatement("INSERT INTO users VALUES(?,?,?,?,?)"); Set the values pstatement.setInt(1, 1); pstatement.setString(2, "Sarath"); pstatement.setString(3, "Chandra"); pstatement.setInt(4, 18); pstatement.setString(5, "
[email protected]"); Execute the statement pstatement.executeUpdate(); Close the Statement pstatement.close();
Programming with JDBC Contd..,
Using JDBC to query database Use SQL statement in the respective statement object of connection object. connection.prepareStatement(“SELECT * FROM users WHERE user_id = ?"); Set the values pstatement.setInt(1, 1); Execute the statement and assign the result in Resultset Object ResultSet rs = pstatement.executeQuery();
Retrieve data from resultset object Close the Statement rs.close();
ORM - Object Relational Mapping
In the previous sections, we have learned how to use JDBC to access relational database. As widely known, Java is an Object-Oriented programming language. We want to work with objects having behavior, not rows and columns of data.
Object-relational paradigm mismatch.
That means we should use an “object model” to represent our domain concepts.
Object Model
Most of the enterprise applications are developed using Object Oriented techniques. The business logic inside the application flows in the form of objects Only saving the objects to the database is a stage where the objects are transformed to text and stored to the database. JavaBeans are used to build an object model. These JavaBeans are called “Plain Old Java Objects” (POJOs).
These POJOs are called as “Persistent classes”.
POJO Programming Rules
Implement a no-argument constructor.
Provide properties with private modifier
These properties maps to columns of a database table.
Declare accessor methods i.e. setters and getters for properties.
Provide an identifier property (optional)
This property maps to the primary key column of a database table
Create a POJO called “Users” i.e. Users Class with POJO Rules, and we need to store this object to the database.
Persistence Class public class Users { public Users() { } private int userId; private String firstName; private String lastName; private int age; private String emailId; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } }
Business Component
Write a business component that can perform different operations on the User object, such as
Insert Update Delete Retrieve
Business Component Class public class UserManager { private Connection openConnection() throws Exception { Class.forName("oracle.jdbc.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "cec", "cec"); return con; } public void cleanup(Connection con, PreparedStatement ps, ResultSet rs) { try { if(rs != null) rs.close(); if(ps != null) ps.close(); if(con != null) con.close(); } catch (Exception e) { } } public void saveUser(Users user) throws Exception { Connection con = openConnection(); PreparedStatement ps = con.prepareStatement("INSERT INTO users VALUES(?,?,?,?,?)"); ps.setInt(1, user.getUserId()); ps.setString(2, user.getFirstName()); ps.setString(3, user.getLastName()); ps.setInt(4, user.getAge()); ps.setString(5, user.getEmailId()); ps.executeUpdate(); cleanup(con,ps,null); }
Business Component Contd.., public Users getUser(Users user) throws Exception { Users u = null; Connection con = openConnection(); PreparedStatement ps = con.prepareStatement("Select * from USERS where user_id = ?"); ps.setInt(1, user.getUserId()); ResultSet rs = ps.executeQuery(); if(rs.next()) { u = new Users(); u.setFirstName(rs.getString(2)); u.setLastName(rs.getString(3)); u.setAge(rs.getInt(4)); u.setEmailId(rs.getString(5)); } cleanup(con, ps, rs); return u; } }
Testing the application UserManager manager = new UserManager(); Users user = new Users(); user.setUserId(2); user.setFirstName("Tejaswi"); user.setLastName("T"); user.setAge(10); user.setEmailId("
[email protected]"); manager.saveUser(user); user.setUserId(1); user = manager.getUser(user); System.out.println("Name >>> " + user.getFirstName() + " " + user.getLastName());
Problems with JDBC Code
Too many SQL statements Using JDBC means you can execute any kind of SQL statements. For a simple task, you have to code many SELECT, INSERT, UPDATE, DELETE statements repeatedly. Too many copy codes When you perform object retrieval, you need to copy the fields in a ResultSet to the properties of an object. When you perform object persistence, you need to copy the properties of an object to the parameters in PreparedStatement. Due to these problems, bug fixing is an accepted stage of an application development process which makes the application too expensive even after the successful completion of development cycle.
ORM Tools
As discussed above, ORM Tools provides data storage and retrieval by direct mapping of Object and Relation without letting the application developer worry about the persistence logic. The most popular ORM Tool is HIBERNATE. Hibernate Goals are Do less work and have a happy DBA. No error prone JDBC code is required.
No manual handling of JDBC ResultSet No Object Conversion No hard coded SQL No Value Object Design Pattern