Presentation is loading. Please wait.

Presentation is loading. Please wait.

Hibernate Dasan Weerarathne.

Similar presentations


Presentation on theme: "Hibernate Dasan Weerarathne."— Presentation transcript:

1 Hibernate Dasan Weerarathne

2 Introduction Hibernate allows to persist the java objects using its’ Object/Relational Mapping (ORM) framework. It is automates ORM and considerably reduces the number of lines of code needed to persist the object in the database. Hibernate can be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans.

3 Advantages of Using Hibernate
Relational Persistence for JAVA Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there is mismatch between how data is represented in objects versus relational database. JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.

4 Advantages of Using Hibernate
Transparent Persistence The automatic mapping of Java objects with database tables. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. (With JDBC this conversion is to be taken care of by the developer manually with lines of code. )

5 Advantages of Using Hibernate
Support for Query Language JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also selects an effective way to perform a database manipulation task for an application.

6 Advantages of Using Hibernate
Database Dependent Code Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

7 Advantages of Using Hibernate
Maintenance Cost With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

8 Advantages of Using Hibernate
Optimize Performance Caching is retention of data, usually in application to reduce disk access. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. (With JDBC, caching is maintained by hand-coding)

9 Advantages of Using Hibernate
Automatic Versioning and Time Stamping By database versioning one can be assured that the changes done by one person is not being roll backed by another one unintentionally. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. (In JDBC there is no check that always every user has updated data. This check has to be added by the developer) When other user tries to save updated tuple to database then it does not allow to save it because this user does not has updated data.

10 Disadvantages of Hibernate
Steep learning curve. Use of Hibernate is an overhead for the applications which are : Simple and use one database that never change Need to put data to database tables, no further SQL queries There are no objects which are mapped to two different tables (Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best choice.)

11 Disadvantages of Hibernate
Anybody wanting to maintain application using Hibernate will need to know Hibernate. For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion. Hibernate does not allow some type of queries which are supported by JDBC. For example It does not allow to insert multiple objects (persistent data) to same table using single query. Developer has to write separate query to insert each object.

12 Hibernate Architecture
Application Persistence Object Hibernate Configuration File Mapping File The above diagram shows that Hibernate is using the database and configuration data to provide persistence services (and persistent objects) to the application. Relational Database

13 Hibernate Architecture Cont…
To use Hibernate, it is required to create Java classes that represents the table in the database and then map the instance variable in the class with the columns in the database. Then Hibernate can be used to perform operations on the database like select, insert, update and delete the records in the table. Hibernate automatically creates the query to perform these operations.

14 Hibernate Architecture Cont…
Hibernate architecture has three main components: Connection Management: Hibernate Connection management service provide efficient management of the database connections. Database connection is the most expensive part of interacting with the database as it requires a lot of resources of open and close the database connection.   Transaction Management: Transaction management service provide the ability to the user to execute more than one database statements at a time.

15 Hibernate Architecture Cont…
Object Relational Mapping : Object relational mapping is technique of mapping the data representation from an object model to a relational data model. This part of the hibernate is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query. Hibernate is very good tool as far as object relational mapping is concern, but in terms of connection management and transaction management, it is lacking in performance and capabilities. So usually hibernate is being used with other connection management and transaction management tools. For example apache DBCP is used for connection pooling with the Hibernate. Hibernate provides a lot of flexibility in use. It is called "Lite" architecture when we only uses the object relational mapping component. While in "Full Cream" architecture all the three component Object Relational mapping, Connection Management and Transaction Management) are used.

16 Hibernate Architecture Cont…
Hibernate is very good tool as far as object relational mapping is concern, but in terms of connection management and transaction management, it is lacking in performance and capabilities. So usually hibernate is being used with other connection management and transaction management tools. For example apache DBCP is used for connection pooling with the Hibernate. Hibernate provides a lot of flexibility in use. It is called "Lite" architecture when we only uses the object relational mapping component. While in "Full Cream" architecture all the three component Object Relational mapping, Connection Management and Transaction Management) are used.

17 Hibernate Architecture Cont…
SessionFactory (org.hibernate.SessionFactory) A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level. Session (org.hibernate.Session) A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier. Persistent objects and collections Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer (e.g. directly as data transfer objects to and from presentation). Transient and detached objects and collections Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session.

18 Hibernate Architecture Cont…
Transaction (org.hibernate.Transaction) A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction, is never optional! ConnectionProvider (org.hibernate.connection.ConnectionProvider) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer.

19 Hibernate Architecture Cont…
TransactionFactory (org.hibernate.TransactionFactory) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer. Extension Interfaces Hibernate offers many optional extension interfaces you can implement to customize the behavior of your persistence layer. See the API documentation for details. Given a "lite" architecture, the application bypasses the Transaction/TransactionFactory and/or ConnectionProvider APIs to talk to JTA or JDBC directly.

20 Creating First Hibernate App
Before you start coding you have to download Hibernate Framework from the following URL. Create Database “vtshibernate” and Create table “contact” at the MySQL database. -- -- Create schema vtshibernate CREATE DATABASE IF NOT EXISTS vtshibernate; USE vtshibernate; -- Definition of table `contact` DROP TABLE IF EXISTS `contact`; CREATE TABLE `contact` ( `ID` int(10) unsigned NOT NULL auto_increment, `FIRSTNAME` varchar(45) NOT NULL, `LASTNAME` varchar(45) NOT NULL, ` ` varchar(45) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

21 First Hibernate App Cont…
Create Java Project using E-clips “FirstHibernateProject” Create package under the src directory. (com.virtusa.contact) Create hibernate.cfg.xml under the src folder. Create contact.hbm.xml under the src folder. Add doc type URL for both .xml files. All XML mappings should declare the doctype shown. The actual DTD may be found at the URL above, in the directory hibernate-x.x.x/src/org/hibernate or in hibernate3.jar. Hibernate will always look for the DTD in its classpath first. If you experience lookups of the DTD using an Internet connection, check your DTD declaration against the contents of your claspath.

22 First Hibernate App Cont…
Completed hibernate.cfg.xml

23 Hibernate for Different Databases
DB2 - org.hibernate.dialect.DB2Dialect HypersonicSQL - org.hibernate.dialect.HSQLDialect Informix - org.hibernate.dialect.InformixDialect Ingres - org.hibernate.dialect.IngresDialect Interbase - org.hibernate.dialect.InterbaseDialect Pointbase - org.hibernate.dialect.PointbaseDialect PostgreSQL - org.hibernate.dialect.PostgreSQLDialect Mckoi SQL - org.hibernate.dialect.MckoiDialect Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect MySQL - org.hibernate.dialect.MySQLDialect Oracle (any version) - org.hibernate.dialect.OracleDialect Oracle 9 - org.hibernate.dialect.Oracle9Dialect Progress - org.hibernate.dialect.ProgressDialect FrontBase - org.hibernate.dialect.FrontbaseDialect SAP DB - org.hibernate.dialect.SAPDBDialect Sybase - org.hibernate.dialect.SybaseDialect Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect

24 First Hibernate App Cont…
Completed contact.hbm.xml

25 First Hibernate App Cont…
<hibernate-mapping>

26 First Hibernate App Cont…
<class> The <Class> element maps the class object with corresponding entity in the database. It also tells what table in the database has to access and what column in that table it should use. Within one <hibernate-mapping> element, several <class> mappings are possible.

27 First Hibernate App Cont…

28 First Hibernate App Cont…

29 First Hibernate App Cont…
<id> The <id> element in unique identifier to identify and object. In fact <id> element map with the primary key of the table. In our code : <id name="id" type="long" column="ID" > primary key maps to the ID field of the table CONTACT. The attributes of the id element are: name: The property name used by the persistent class. column: The column used to store the primary key value. type: The Java data type used. unsaved-value: This is the value used to determine if a class has been made persistent. If the value of the id attribute is null, then it means that this object has not been persisted.

30 First Hibernate App Cont…
< generator> There are shortcut names for the built-in generators as shown below: <id name="id" type="long" column="person_id"> <generator class="sequence"> <param name="sequence">person_id_sequence</param> </generator> </id> <id name="id" type="long" column="person_id" unsaved-value="0"> <generator class="identity"/>

31 The <generator> method is used to generate the primary key for the new record. Here is some of the commonly used generators :   * Increment - This is used to generate primary keys of type long, short or int that are unique only. It should not be used in the clustered deployment environment.   *  Sequence - Hibernate can also use the sequences to generate the primary key. It can be used with DB2, PostgreSQL, Oracle, SAP DB databases.    * Assigned - Assigned method is used when application code generates the primary key. 

32 First Hibernate App Cont…
< property > The property elements define standard Java attributes and their mapping into database schema. The property element supports the column child element to specify additional properties, such as the index name on a column or a specific column type.

33 First Hibernate App Cont…

34 First Hibernate App Cont…
Create the Java class called Contact having getters and setters:

35 First Hibernate App Cont…
Create Test Class to Insert new Record to the Database:

36 First Hibernate App Cont…
Your Final Project Should appear as below:

37 Second Hibernate Example
Create new project to maintain following Book table. Hint: It is enough to add Book Record to the table.

38 Third Hibernate Example
Create new project to maintain Insurance Information: Hit: The program should provide functionality to add Insurance Information and also should provide functionality to modify the given Insurance information. Now Modify the program to delete a given insurance Information package com.virtusa.application; import java.util.Date; import org.hibernate.Session; import org.hibernate.Query; import org.hibernate.cfg.Configuration; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import com.virtusa.insurance.Insurance; Session session = null; public class InsuranceOperations { Transaction transaction = null; SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); { public InsuranceOperations() } transaction = session.beginTransaction(); session =sessionFactory.openSession(); public void createNewAccount(String insuranceName,int amount,Date dt) try Insurance ins = new Insurance(); ins.setInvestementDate(dt); ins.setInvestementAmount(amount); ins.setInsuranceName(insuranceName); session.save(ins); System.out.println("Added successfully!"); session.close(); transaction.commit(); catch(Exception e) System.out.println(e.getMessage()); finally session.flush(); public void updateAccount(int id,String insuranceName,int amount,Date dt) Insurance ins = (Insurance)session.get(Insurance.class, new Long(id)); session.update(ins); System.out.println("Update successfully!"); public void deleteAccount(int id) String hql = "delete from Insurance where lngInsuranceId =" + id; if (row == 0) int row = query.executeUpdate(); Query query = session.createQuery(hql); System.out.println("Doesn't deleted any row!"); else System.out.println("Deleted Row: " + row); public void deleteAccountUsingSession(int id) session.delete(ins); System.out.println("Deleted successfully!"); ******************************************************************************************************************************** InsuranceOperations in1 = new InsuranceOperations(); //in1.createNewAccount("Virtusa Coporation - City", , new Date()); //in1.updateAccount(2, "Virtusa Coporation - World", , new Date()); //in1.deleteAccount(1); in1.deleteAccountUsingSession(3);

39 Hibernate Query Language
HQL is much like SQL  and are case-insensitive, except for the names of the Java Classes and properties. Hibernate Query Language is used to execute queries against database. Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application. HQL is based on the relational object models and makes the SQL object oriented. Hibernate Query Language uses Classes and properties instead of tables and columns. Hibernate Query Language is extremely powerful and it supports Polymorphism, Associations, Much less verbose than SQL.

40 Advantage of using HQL Full support for relational operations:
HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is easy to use. This eliminates the need of creating the object and populate the data from result set.

41 Advantage of using HQL Polymorphic Queries:
HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any. Support for Advance features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls. Database independent: Queries written in HQL are database independent (If database supports the underlying feature).

42 Understanding HQL Syntax
Any Hibernate Query Language may consist of following elements: Clauses (from, select, where, order by, group by) Aggregate functions (avg, min, max, sum, count) Sub queries (query within another query)

43 Create following Data Set
ID insurance_name invested_amount investement_date 1 Car Insurance 1000 :00:00 2 Life Insurance 100 :00:00 3 500 :00:00 4 2500 :00:00 5 Dental Insurance :00:00 6 900 :00:00 7 Travel Insurance 2000 :00:00 8 600 :00:00 9 Medical Insurance 700 :00:00 10 11 Home Insurance 800 12 750 :00:00 13 Motorcycle Insurance :00:00 14 780 /*Table structure for table `insurance` */ drop table if exists `insurance`; CREATE TABLE `insurance` ( `ID` int(11) NOT NULL default '0', `insurance_name` varchar(50) default NULL, `invested_amount` int(11) default NULL, `investement_date` datetime default NULL, PRIMARY KEY (`ID`) ) TYPE=MyISAM; /*Data for the table `insurance` */ insert into `insurance` values (1,'Car Insurance',1000,' :00:00'); insert into `insurance` values (2,'Life Insurance',100,' :00:00'); insert into `insurance` values (3,'Life Insurance',500,' :00:00'); insert into `insurance` values (4,'Car Insurance',2500,' :00:00'); insert into `insurance` values (5,'Dental Insurance',500,' :00:00'); insert into `insurance` values (6,'Life Insurance',900,' :00:00'); insert into `insurance` values (7,'Travel Insurance',2000,' :00:00'); insert into `insurance` values (8,'Travel Insurance',600,' :00:00'); insert into `insurance` values (9,'Medical Insurance',700,' :00:00'); insert into `insurance` values (10,'Medical Insurance',900,' :00:00'); insert into `insurance` values (11,'Home Insurance',800,' :00:00'); insert into `insurance` values (12,'Home Insurance',750,' :00:00'); insert into `insurance` values (13,'Motorcycle Insurance',900, ' :00:00'); insert into `insurance` values (14,'Motorcycle Insurance',780 ,' :00:00');

44 Writing HQL Queries Write HQL Query to View all the available data at the table. Write a HQL query to get total count of the all the records. Write a HQL query to get count of the insurance based on the Amount. select count(*) from insurance group by id; String SQL_QUERY = "select count(*)from Insurance insurance"; select invested_amount, count(*) from insurance group by invested_amount; String SQL_QUERY = "select insurance.investementAmount, count(*) from Insurance insurance group by insurance.investementAmount";

45 Writing HQL Queries Cont…
Write a HQL query to get count of the insurance based on the Insurance Name. Write HQL query to get the Avg/Max/Min of the total Amounts. select insurance_name, count(*) from insurance group by insurance_name; String SQL_QUERY = "select insurance.insuranceName, count(*) from Insurance insurance group by insurance.insuranceName"; select avg(invested_amount) from insurance; String SQL_QUERY = "select avg(insurance.investementAmount) from Insurance insurance"; String SQL_QUERY = " from Insurance as  insurance order by insurance.insuranceName";

46 Criteria Query The interface org.hibernate.Criteria represents a query against a particular persistent class. The Session is a factory for Criteria instances. An individual query criterion is an instance of the interface org.hibernate.criterion.Criterion. The class org.hibernate.criterion.Restrictions defines factory methods for obtaining certain built-in Criterion types. Ref:

47 Criteria Query Cont… Criteria Interface provides the following methods
Description add The Add method adds a Criterion to constrain the results to be retrieved. addOrder Add an Order to the result set. createAlias Join an association, assigning an alias to the joined entity createCriteria This method is used to create a new Criteria, "rooted" at the associated entity. setFetchSize This method is used to set a fetch size for the underlying JDBC query. setFirstResult This method is used to set the first result to be retrieved. setMaxResults This method is used to set a limit upon the number of objects to be retrieved. uniqueResult    This method is used to instruct the Hibernate to fetch and return the unique records from database.

48 Criteria Query Cont… Class Restriction provides built-in criterion via static factory methods Method Description Restriction.allEq    This is used to apply an "equals" constraint to each property in the key set of a Map Restriction.between    This is used to apply a "between" constraint to the named property Restriction.eq    This is used to apply an "equal" constraint to the named property Restriction.ge    This is used to apply a "greater than or equal" constraint to the named property Restriction.gt    This is used to apply a "greater than" constraint to the named property Restriction.idEq This is used to apply an "equal" constraint to the identifier property Restriction.ilike    This is case-insensitive "like", similar to Postgres ilike operator Restriction.in This is used to apply an "in" constraint to the named property

49 Criteria Query Cont… Method Description Restriction.isNotNull
This is used to apply an "is not null" constraint to the named property Restriction.isNull   This is used to apply an "is null" constraint to the named property Restriction.le  This is used to apply a "less than or equal" constraint to the named property Restriction.like This is used to apply a "like" constraint to the named property Restriction.lt This is used to apply a "less than" constraint to the named property Restriction.ltProperty This is used to apply a "less than" constraint to two properties Restriction.ne  This is used to apply a "not equal" constraint to the named property Restriction.neProperty This is used to apply a "not equal" constraint to two properties Restriction.not   This returns the negation of an expression Restriction.or  This returns the disjuction of two expressions

50 Criteria Query Cont… Criteria Query Exercises 01:
Create Sample program to display Insurance records which are having Amount in-between 1000 and 2500. (Make sure that you should display maximum only 5 records) Criteria Query Exercises 02: Create sample program to return Insurance records which are having investment date in-between 2005/01/01 to 2005/03/03.  Criteria crit =  session.createCriteria(Insurance.class);   crit.add(Expression.between(" investementAmount", new Integer(1000),    new Integer(2500))); // Between condition   crit.setMaxResults(5); // ********************************************************************** DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date startDate = (Date)format.parse(" :00:00"); Date endDate = (Date)format.parse(" :00:00"); crit.add(Restrictions.between("investementDate", new Date(startDate.getTime()), new Date(endDate.getTime()))); crit.setMaxResults(5); // restrict Max number of rows return

51 Hibernate Relationship Mapping
Hibernate Support for the following relationships: one-to-one one-to-many many-to-many many-to-one We can simulate the all these relationships in our Java. With the help of Hibernate relationships we can define these associations among the persistence unit and use in the Java program

52 One-to-One Relationships
In case of one-to-one relationships, each row in table A linked to only one row in table B. Here we will implement one-to-one relationship between two entries Employee and EmployeeAddress. We are using two tables employee and employee_address and java entities Employee and EmployeeAddress maps respectively.

53 One-to-One Relationships Cont.
ER Diagram For the Relationship:

54 One-to-One Relationships Cont.
Employe.hmb.xml:

55 One-to-One Relationships Cont.
EmployeAddress.hmb.xml:

56 One-to-One Relationships Cont.
Driver Program:

57 One-to-Many Relationships
In case of one-to-many relationships, each row in table A linked to multiple rows in table B. Here we will implement one-to-many relationship between two entries Group and Story. There exists multiple stories under a group. We are using two tables grouptable and story and java entities Group and Story maps respectively.

58 One-to-Many Relationships Cont.
ER Diagram For the Relationship:

59 One-to-Many Relationships Cont.
Group.hmb.xml:

60 One-to-Many Relationships Cont.
Story.hmb.xml:

61 One-to-Many Relationships Cont.
Driver Program:

62 One-to-Many Relationships Cont.
Display Stories for a given Group Id:

63 Many-to-Many Relationships
In case of many-to-many relationships, each row in table A linked to multiple rows in table B and vice versa. Here we will implement many-to-many relationship between two entries Author and Book. A book might be authored by multiple author and one author might author many books. We are using two tables author and book and java entities Author and Book maps respectively.

64 Many-to-Many Relationships Cont
ER Diagram For the Relationship:

65 Many-to-Many Relationships Cont
Author.hmb.xml:

66 Many-to-Many Relationships Cont
Book.hmb.xml:

67 Many-to-Many Relationships Cont
Driver Program:

68 Many-to-Many Relationships Cont
Displaying Book Information for a given Author:

69 Many-to-One Relationships
A many-to-one relationship is where one entity contains values that refer to another entity (a column or set of columns) that has unique values. In relational databases, these many-to-one relationships are often enforced by foreign key/primary key relationships. Here we will implement Many-to-one relationship between two entries Group and Story. (Example Used under the topic One-to-Many)

70 Many-to-One RelationshipsCont.

71 Many-to-One Relationships Cont.
In the Entity Story.java we have to define Group object and getter and setters for the same.

72 Many-to-One Relationships Cont.
Modified Story.hmb.xml:

73 Many-to-One Relationships Cont.
The below code will load the Story entity whose primary key is 4, and then retrieved the parent Group.

74 Thank You….!


Download ppt "Hibernate Dasan Weerarathne."

Similar presentations


Ads by Google