1 / 74

Hibernate

Hibernate. Dasan Weerarathne. 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.

tale
Download Presentation

Hibernate

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Hibernate DasanWeerarathne

  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)

  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.

  12. Hibernate Architecture Application Persistence Object Hibernate Configuration File Mapping File 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.

  16. Hibernate Architecture Cont…

  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.

  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.

  20. Creating First Hibernate App • Before you start coding you have to download Hibernate Framework from the following URL.http://olex.openlogic.com/packages/hibernate#package_detail_tabs • Create Database “vtshibernate” and Create table “contact” at the MySQL database.

  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.

  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>

  27. First Hibernate App Cont…

  28. First Hibernate App Cont…

  29. First Hibernate App Cont… • <id>

  30. First Hibernate App Cont… • < generator> There are shortcut names for the built-in generators as shown below:

  31. First Hibernate App Cont… • < property >

  32. First Hibernate App Cont…

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

  34. First Hibernate App Cont… • Create Test Class to Insert new Record to the Database:

  35. First Hibernate App Cont… • Your Final Project Should appear as below:

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

  37. 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

  38. 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.

  39. 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.

  40. 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.

  41. 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)

  42. Create following Data Set

  43. 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.

  44. 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.

  45. 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: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html

  46. Criteria Query Cont… • Criteria Interface provides the following methods

  47. Criteria Query Cont… • Class Restriction provides built-in criterion via static factory methods

  48. Criteria Query Cont…

  49. 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. (Make sure that you should display maximum only 5 records)

More Related