Uploaded on

Hibernate tutorial for beginners - Learn Hibernate 3.x starting from environment setup, Object Relational Mapping (ORM), Query Language, Native SQL, Caching, Interceptors, Persistent Classes, …

Hibernate tutorial for beginners - Learn Hibernate 3.x starting from environment setup, Object Relational Mapping (ORM), Query Language, Native SQL, Caching, Interceptors, Persistent Classes, Persistent Objects, Collections, Associations and components, and Hibernate tools.

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
390
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
77
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Hibernate 3.5 Prepared By Mumbai Academics https://www.facebook.com/mumbai.academics.group
  • 2. Hibernate 3.5 Lesson 01: Introduction to ORM and its Need
  • 3. Lesson Objectives • In this lesson, you will learn about: – Object/Relation Mapping – Object-relation Impedence Mismatch – Hibernate 3.5 – Building a Simple Application 3
  • 4. Demo • Down This Files To Get Demos
  • 5. What is Object/Relation Mapping? • It means how we will map the relational world with the object world. – In the relational world, the data is in the form of a table that contains rows and column. – In the object world, the data is in the form of an object. 5
  • 6. An ORM Solution • It consists of: – An API, to perform CRUD (Create, Read, Update, Delete) operations on objects of persistent classes – A language to specify queries that refer to classes and properties of classes – A facility, to specify mapping metadata – A technique, for the ORM implementation to interact with transactional objects to perform dirty checking. Lazy association, fetching, and other optimization functions.
  • 7. Why ORM? • It “shields” developers from “messy” SQL • This view holds that object oriented developers cannot be expected to understand SQL or relational databases • Some of the benefits of ORM and Hibernate are: – – – – Productivity Maintainability Performance Vendor independence
  • 8. Persistence and Relational Database • Persistence means that we would like our application's data to outlive the applications process. • In Java terms, we would like the state of (some of) our objects to live beyond the scope of the JVM so that the same state is available later. • Hibernate is concerned with data persistence as it applies to relational databases (RDBMS). In the world of object-oriented applications, there is often a discussion about using an object database (ODBMS) as opposed to a RDBMS.
  • 9. Object-Relation Impedence Mismatch • Object-relational Impedence Mismatch' means that object models and relational models do not work very well together. RDBMSs represent data in a tabular format, whereas object-oriented languages, such as Java, represent it as an interconnected graph of objects. Loading and storing graphs of objects using a tabular relational database exposes us to mismatch problems... – Granularity – Inheritance (subtypes) – Identity 9
  • 10. Granularity • Sometimes you will have an object model, which has more classes than the number of corresponding tables in the database (The object model is more granular than the relational model) and vice versa. 10
  • 11. Subtypes (inheritance) • Inheritance is a natural paradigm in objectoriented programming languages. However, RDBMSs do not define anything similar on the whole. 11
  • 12. Identity • An RDBMS defines exactly one notion of 'sameness': the primary key. Java, however, defines both object identity (a==b) and object equality (a.equals(b)). 12
  • 13. Introduction to Hibernate 3.5 • Hibernate is an open source ORM implementation • It mediates the application’s interaction with a relational database, leaving the developer free to concentrate on the business problem at hand. • Hibernate is an non-intrusive solution. 13
  • 14. Introduction to Hibernate 3.5 • Hibernate 3.5 is an implementation of the Java Persistence API standard that replaced older Java persistence solutions such as the entity beans from Enterprise Java Beans 2. • Hibernate 3.5 has introduced standard persistence mechanism JPA and Infispan as caching mechanism. 14
  • 15. Hibernate Features • No build time bytecode generation • No special database tables • Flexible O/R mapping
  • 16. Hibernate Features (continued) • Uses get/set methods and empty parameter constructor • Supports fine-grained objects • Lazy initialization • Automatic primary key generation with multiple strategies
  • 17. Hibernate Features (continued) • • • • Support for transactions including optimistic locking Built in connection pooling or use popular connection pools Built in caching (Hibernate Dual Layer Cache Architecture) Abstracts the variations in dialects between databases. For example: – <property name="dialect">org.hibernate.dialect.HSQLDialect</property> • Query by criteria – For a complete set of features see http://www.hibernate.org
  • 18. Why Hibernate? • Impedance mismatch – Object-oriented vs. relational • Java developers are not database developers – Reduce the need for developers to know and fully understand database design, SQL, performance tuning – Increase portability across database vendors • Increase performance by deferring to experts – Potential decrease in database calls – More efficient SQL statements – Hibernate cache usage 18
  • 19. Disadvantages of Hibernate • Hibernate may be slower than JDBC • Hibernate’s connection pool is not great, but it works with the other popular connection pools • Support for HQL (Hibernate Query Language) syntax cannot be found outside of Hibernate
  • 20. Hibernate Components
  • 21. Overview of Hibernate API in a layered Architecture
  • 22. Architecture Classes • SessionFactory (org.hibernate.SessionFactory) – A threadsafe (immutable) cache of compiled mappings for a single database. – A factory for Session and a client of ConnectionProvider. • 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.
  • 23. Architecture Classes • 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.
  • 24. Configuration • Three modes of configuration – Using properties file – Programmatic – Declarative using XML configuration file
  • 25. XML Configuration File <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class"> org.hsqldb.jdbcDriver</property> ……….. <mapping resource="events/Event.hbm.xml"/> <mapping resource="events/Person.hbm.xml"/> </session-factory> </hibernate-configuration>
  • 26. Use Configuration to get SessionFactory • When all mappings have been parsed by the Configuration, the application must obtain a factory for Session instances. This factory is intended to be shared by all application threads: – SessionFactory sessions = cfg.buildSessionFactory();
  • 27. JDBC Connections • Usually, you want to have the SessionFactory to create and pool JDBC connections for you. If you take this approach, opening a Session is as simple as: • Session session = sessions.openSession(); – // open a new Session • As soon as you do something that requires access to the database, a JDBC connection will be obtained from the pool
  • 28. JDBC Connections • Hibernate will obtain (and pool) connections using java.sql.DriverManager, if you set the following properties:
  • 29. JDBC Connections • For use inside an application server, you should almost always configure Hibernate to obtain connections from an application server Datasource registered in JNDI. You'll need to set at least one of the following properties:
  • 30. Use XML Configuration to Get sessionFactory • Obtain SessionFactory as – SessionFactory sf = new Configuration().configure().buildSessionFactory(); • You can pick a different XML configuration file using – SessionFactory sf = new Configuration() .configure("catdb.cfg.xml") .buildSessionFactory();
  • 31. Building a Hibernate Application • Define the domain model • Setup your Hibernate configuration – hibernate.cfg.xml • Create the domain object mapping files – <domain_object>.hbm.xml • Make Hibernate aware of the mapping files – Update the hibernate.cfg.xml with list of mapping files 31
  • 32. Review – Questions • Implement a HibernateUtil class. – Usually taken from the Hibernate documentation • Write your code 32
  • 33. Account Object/Table
  • 34. hibernate.cfg.xml
  • 35. hibernate.cfg.xml
  • 36. hibernate.cfg.xml
  • 37. Configuring Hibernate • There are multiple ways to configure Hibernate and an application can leverage multiple methods at once • Hibernate will look for and use configuration • properties in the following order – hibernate.properties (when ‘new Configuration()’ is called) – hibernate.cfg.xml (when ‘configure()’ is called on Configuration) – Programatic configuration settings
  • 38. Object Mapping Files
  • 39. Account.hbm.xml Mapping File
  • 40. Hibernate ID Generators • Native: Leverages underlying database method for generating ID(sequence, identity, etc…) • Increment: Automatically reads max value of identity column and increments by 1 • UUID: Universally unique identifier combining IP & Date (128-bit) Many more…
  • 41. Some more ID generetaors
  • 42. Identify Mapping Files in the hibernate.cfg.xml
  • 43. HibernateUtil • Convenience class to handle building and obtaining the Hibernate Session Factory. – Use recommended by the Hibernate org • Session Factory is thread-safe – Singleton for the entire application • Used to build Hibernate ‘Sessions’ – Hibernate Sessions are NOT thread safe – One per thread of execution
  • 44. HibernateUtil
  • 45. Testing the Code
  • 46. Demo • StartingHibernate Demo
  • 47. Hibernate 3.5 Lesson 2: The Persistence Life Cycle
  • 48. Lesson Objectives • After completing this lesson, you will be able to explain the following topics: – – – – – Hibernate Object Life Cycle Persistent State Transient Object Removed State Detached State 48
  • 49. Hibernate Object Life Cycle
  • 50. Transient State • All objects start off in the transient state – Account account = new Account(); • account is a transient object • Hibernate is not aware of the object instance • Not related to database row – No value for accountId • Garbage collected when no longer referenced by any other objects 50
  • 51. Persistent State • Hibernate is aware of, and managing, the object • It has a database ID • This is the only state where objects are saved to the database • Objects are made persistent through calls against the Hibernate session • – session.save(account); – session.lock(account); • – session.update(account); – session.merge(account);
  • 52. Persistent State (Contd…) •
  • 53. Removed State • A previously persistent object that is deleted from the database. – session.delete(account); • Java instance may still exist, but it is ignored by Hibernate – Any changes made to the object are not saved to the database – Picked up for garbage collection once it falls out of scope • Hibernate does not null-out the in-memory object
  • 54. Removed State (Contd…) 54
  • 55. Detached State • A persistent object that is still referenced after closure of the active session. – session.close() changes object’s state from persisted to detached • Still represents a valid row in the database • No longer managed by Hibernate. – Changes made to detached objects are not saved to the database while object remains in the detached state 55
  • 56. Detached State (Contd…) 56
  • 57. Persistence Context • Managed object environment – No API or concrete object to reference, just conceptual – Thought of as containing: • Graph of managed persistent instances • List of SQL statements to send to the database • Each Hibernate session is said to have one ‘persistence context’. 57
  • 58. Persistence Context (Contd…) 58
  • 59. Flushing the Context • The process of synchronizing the memory state with the database, usually only at the end of a unit of work, is called flushing Submits the stored SQL statements to the database • Occurs when: – Transactions commit() or rollback() is called – session.flush() is called explicitly – Before a query is executed • If stored statements would affect the results of the query
  • 60. Flushing Modes • Flush modes – session.setFlushMode() • FlushMode.AUTO: Default. Called as described above • FlushMode.COMMIT: Not flushed before queries • FlushMode.MANUAL: Only when explicit flush() is called
  • 61. CRUD (Create, Read, Update, Delete) • Creating a row in database through hibernate using • save() method
  • 62. CRUD (Contd…) • Reading data from the database using hibernate
  • 63. CRUD - Reading Data • Updating the data
  • 64. CRUD - Updating the Record in Database • Any persistent object returned by get() or any other kind of query is already associated with the current Session and transaction context. • It can be modified, and its state will be synchronized with the database.
  • 65. CRUD - Difference Between load() & get()
  • 66. CRUD - Updating detached Instance
  • 67. CRUD - Updating detached Instance (Contd…) • The lock() method also allows an application to reassociate • an object with a new session. However, the detached instance • has to be unmodified! //just reassociate: sess.lock(fritz, LockMode.NONE); //do a version check, then reassociate: sess.lock(izi, LockMode.READ); //do a version check, using SELECT ... FOR UPDATE, then reassociate: sess.lock(pk, LockMode.UPGRADE);
  • 68. CRUD - Delete • In order to allow convenient removal of entities from the database, the Session interface provides a delete() method, as follows: public void delete(Object object) throws HibernateException
  • 69. CRUD – Delete (Contd…) • Session session = sessions.openSession(); • Transaction tx = session.beginTransaction(); • session.delete(user); tx.commit(); session.close(); • In this case, the call to delete() undertakes two actions: It associates the object with the session and then schedules the object for deletion, executed on tx.commit().
  • 70. Refreshing Entities • Hibernate provides a mechanism to refresh persistent objects from their database representation. • Use one of the refresh() methods on the Session interface to refresh an instance of a persistent object, as follows: public void refresh(Object object) throws HibernateException public void refresh(Object object, LockMode lockMode) throws HibernateException
  • 71. Demo Demo: HibernateCRUD
  • 72. Transactions • A transaction is a unit of work guaranteed to behave as if you have exclusive use of the database. If you wrap your work in a transaction, the behavior of other system users will not affect your data. A transaction can be started, committed to write data to the database, or rolled back to remove all changes from the beginning onward . • Transactions and locking are intimately related—the locking techniques chosen to enforce a transaction can determine both the performance and likelihood of success of the transaction.
  • 73. Transactions (Contd…) • To achieve this, you obtain a Transaction object from the database (beginning the transaction) and manipulate the session as shown in the following code:
  • 74. Hibernate 3.5 Lesson 3: Hibernate Association and Collection Mapping
  • 75. Lesson Objectives • After completing this lesson, you will be able to explain the following topics: • Unidirectional Associations – many-to-one – one-to-one • Bi-directional Associations – one-to-many/many-to-one – one-to-one 75
  • 76. Lesson Objectives (Contd…) • Collection Mapping – Association Using SET
  • 77. Associations • Association represents relationship between entities. • There is no directionality involved in relational world, its just a matter of writing a query. • But there is notion of directionality which is possible in java. • For hibernate association are of two types: – Unidirectional – Bidirectional
  • 78. Unidirectional Associations (many-toone) • <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <many-to-one name="address" class=“Address” column="addressId" not-null="true"/ cascade=“all”> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> </class>
  • 79. One-To-One <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> </class> <class name="Address"> <id name="id" column="personId"> <generator class="foreign"> <param name="property">person</param> </generator> </id> <one-to-one name="person" constrained="true"/> </class>
  • 80. Using many-to-one Element to Create one-to-one Relationship
  • 81. Student.hbm.xml <class name="com.patni.student.Student" table="STUDENT"> <id name="studentId" type="long" column="STUDENT_ID "> <generator class="native" /></id> <property name="studentName" type="string" notnull="true"length="100" column="STUDENT_NAME" /> <many-to-one name="studentAddress"class="com.patni.student.Address “ column="STUDENT_ADDRESS"notnull="true" cascade="all" unique="true" /> </class>
  • 82. Address.hbm.xml <class name="com.patni.student.Address" table="ADDRESS"> <id name="addressId" type="long" column="ADDRESS_ID" > <generator class="native" /> </id> <property name="street" column="ADDRESS_STREET" type="string"length="250" /> <property name="city" column="ADDRESS_CITY" type="string"length="50" /> <property name="state" column="ADDRESS_STATE" type="string"length="50" /> <property name="zipcode" column="ADDRESS_ZIPCODE" type="string"length="10" /> </class
  • 83. Student class public class Student implements java.io.Serializable { private long studentId; private String studentName; private Address studentAddress; public Student() { } . . .
  • 84. Address class public class Address implements java.io.Serializable { private long addressId; private String street; private String city; private String state; private String zipcode; public Address() { }
  • 85. Demo • One_to_one • One_to_many
  • 86. Bidirectional Associations one-to-many / many-to-one <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <many-to-one name="address" column="addressId“ not-null="true"/> </class> <class name="Address"> <id name="id" column="addressId"> <generator class="native"/> </id> <set name="people" inverse="true"> <key column="addressId"/> <one-to-many class="Person"/> </set> </class>
  • 87. Bidirectional Associations(fk) one-toone A bidirectional one-to-one association on a foreign key is common: <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <many-to-one name="address" column="addressId" – unique="true" not-null="true"/> </class> <class name="Address"><id name="id" column="addressId"> – <generator class="native"/></id> <one-to-one name="person" property-ref="address"/> </class>
  • 88. Bidirectional Associations(pk) one-toone A bidirectional one-to-one association on a primary key uses the special id generator: <class name="Person"> <id name="id" column="personId"> <generator class="native"/> </id> <one-to-one name="address"/> </class> <class name="Address"> <id name="id" column="personId"> – <generator class="foreign"> <param name="property">person</param> </generator> </id> <one-to-one name="person" – constrained="true"/> </class>
  • 89. Collection Mapping • Association & Collection mapping tags are practically identical. • Hibernate Collection Types – <set> • Unordered/Ordered, requiring value column – <map> • Unordered/Ordered, requiring key and value columns
  • 90. Collection Mapping (Contd…) – <list> • Ordered, requiring an index column on the referenced object table – <array> • Map to Java Type and Primitive Arrays • Ordered, requiring an index column on the referenced object table – <bag> • No direct implementation available in Java • Unordered/ordered collection allowing duplicates
  • 91. Collection Mapping (Contd…) • Realized through Collection/List • Requires value column – <idbag> • Used for many-to-many relationships • Same as Bag, but with additional identifier column used for surrogate keys • Requires an ID Generator just like Entity classes
  • 92. Association as <set> • Maps to a ‘Set’ interface – Impls include HashSet, TreeSet, etc… • Can be optionally sorted – EBiller has many EBills (1:M / M:1) • EBill Mapping <many-to-one name="ebiller" column="EBILLER_ID" class="courses.hibernate.vo.EBiller" /> • EBiller Mapping <set name="ebills" inverse="true" sort="unsorted|natural|my.custom.MyComparator"> <key column="EBILLER_ID" not-null="true"/> <one-to-many class="courses.hibernate.vo.EBill"/> </set>
  • 93. Demo • • • • One_to_one One_to_many hibernateOneToManybidirectional OneToManyBiDirectionalWithSet
  • 94. Hibernate 3.5 Lesson 04: Transaction Management
  • 95. Lesson Objectives • In this lesson, you will learn: – Programmatic Transaction Management – Declarative Transaction Management – Using Data Source for Transaction Management
  • 96. Transaction • Represents a single unit-of-work • All or nothing – either all of the actions get committed or the entire effort fails. • Example: – Transfer Money Between Accounts – Step 1: Withdraw $500 from Savings Account – Step 2: Deposit $500 into Checking Account • What happens if the system crashes after Step 1, but before Step 2?
  • 97. Transaction (continued) • Hibernate communicates with the database via a JDBC Connection; hence it must support both APIs. In a stand-alone (or web-based) application, only the JDBC transaction handling is available; in an application server, Hibernate can use JTA. • Since we would like Hibernate application code to look the same in both managed and nonmanaged environments, Hibernate provides its own abstraction layer, hiding the underlying transaction API.
  • 98. Transaction • Hibernate needs a way to abstract the various transaction strategies from the environment. Hibernate has its own Transaction class that is accessible from the Session interface, demonstrated here: • In this example, factory is an initialized SessionFactory instance. This code creates an instance of the org.hibernate.Transaction class and then commits the Transaction instance.Notice that you don't need to call session.flush(). Committing a transaction automatically flushes the Session object. The Event instance is persisted to the database when the transaction is committed. The transaction strategy you use (JDBC or JTA) doesn't matter to the application code-it's set in the Hibernate configuration file. •
  • 99. Transaction • The transaction.factory_class property defines the transaction strategy that Hibernate uses. The default setting is to use JDBC transactions since they're the most common. To use JTA transactions, you need to set the following properties in hibernate.cfg.xml: • The transaction.factory_class property tells Hibernate that you'll be using JTA transactions. Currently, the only other option to JTA is JBDC transactions, which is the default. JTA transactions are retrieved from a JNDI URI, which is specified using the jta.User-Transaction property. If you don't know the URI for your specific application server, the default value is java:comp/UserTransaction.
  • 100. Programmatic Transactions in Hibernate • org.hibernate.Transaction – begin(); – commit(); – rollback(); – setTimeout(); – Obtained through session • session.beginTransaction(); • session.getTransaction(); – Works in a non-managed plain JDBC environment and also with application servers using JTA
  • 101. Programmatic Transactions in Hibernate – javax.transaction.UserTransaction • Java Transaction API (JTA) version • Hibernate recommends this as the primary choice whenever it’s available
  • 102. Programmatic Transactions in Native Hibernate try { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); // session obtains connection and sets autoCommit(false) session.beginTransaction(); // ... // modify and call persistent methods on various objects // ... // flush the Persistence Context and commit to the database session.getTransaction().commit(); catch (HibernateException he) { // roll back if an exception occurs session.getTransaction().rollback(); } finally { // close session and return connection to pool session.close(); }
  • 103. Programmatic Transactions in Hibernate with JTA • Hibernate recommends leveraging JTA over native Hibernate APIs when available • Within a JTA environment, actions are tied to the JTA system transaction • Need to tell Hibernate about JTA, and the vendor specific TransactionManager
  • 104. Programmatic Transactions in Hibernate with JTA
  • 105. Programmatic Transactions in Hibernate with JTA <session-factory> ... <property name="current_session_context_class"> jta </property> <propertyname="transaction.factory_class"> org.hibernate.transaction.JTATransactionFactory </property> <property name="transaction.manager_lookup_class"> <!-- selected on a per-vendor basis --> org.hibernate.transaction.JBossTransactionManagerLookup </property> ... </session-factory>
  • 106. Declarative Transactions • Pushes transaction management and responsibility to the app server. – Container-managed-transactions • Doesn’t require extra boilerplate code – Much cleaner and easier to read – Easier to follow the business logic • No need to manually start and stop transactions!
  • 107. Declarative Transactions <!-- Declarative Transaction Management --> <property name="current_session_context_class">jta</property > <property name="transaction.factory_class"> org.hibernate.transaction.CMTTransactionFactory</propert y> <property name="transaction.manager_lookup_class"> org.hibernate.transaction.JBossTransactionManagerLookup </property>
  • 108. JBoss Datasource – lecture6DS.xml <?xml version="1.0" encoding="UTF-8"?> <datasources> <local-tx-datasource> <jndi-name>Lecture6DS</jndi-name> <!-- Oracle Configuration --> <connection-url> jdbc:oracle:thin:@localhost:1521:XE</connection-url> <driver-class> oracle.jdbc.driver.OracleDriver </driver-class> <user-name>lecture6</user-name> <password>lecture6</password> <min-pool-size>5</min-pool-size> <max-pool-size>100</max-pool-size> </local-tx-datasource> </datasources>
  • 109. Demo • Herbernate_with_Datasource
  • 110. Hibernate 3.5 Lesson 05: Searches and Queries
  • 111. Lesson Objectives • In this lesson, you will learn: – Hibernate Query Language(HQL) – Hibernate Projections 111
  • 112. Hibernate Query Language(HQL) • HQL is a language for talking about “sets of objects” • It unifies relational operations with object models • HQL is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. • HQL is a language with its own syntax and grammar.
  • 113. Hibernate Query Language • 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
  • 114. Hibernate Query Language • Make SQL be object oriented – – – – Classes and properties instead of tables and columns Polymorphism Associations Much less verbose than SQL • Full support for relational operations – – – – – – Inner/outer/full joins, cartesian products Projection Aggregation (max, avg) and grouping Ordering Subqueries SQL function calls
  • 115. Why to use HQL? • Full support for relational operations • Return result as Object • Polymorphic Queries – Polymorphic queries results the query results along with all the child objects if any • Easy to Learn • 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 • Database independent
  • 116. The from Clause and Aliases • Simple shortcut query to select all objects from the Product table “from Product as p or from Product as product” • The from clause is very basic and useful for working directly with objects. • String SQL_QUERY ="from Insurance insurance"; Query query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Insurance insurance=(Insurance)it.next(); System.out.println("ID: " +insurance.getLngInsuranceId()); System.out.println("First Name: " + insurance.getInsuranceName()); } session.close();
  • 117. HQL select Clause • The select clause provides more control over the result set than the from clause. If you want to obtain the properties of objects in the result set, use the select clause • //Create Select Clause HQL String SQL_QUERY ="Select insurance.lngInsuranceId, insurance.insuranceName," + "insurance.investementAmount, insurance.investementDate from Insurance insurance"; Query query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Object[] row = (Object[]) it.next(); System.out.println("ID: " + row[0]); System.out.println("Name: " + row[1]); System.out.println("Amount: " + row[2]); }session.close();
  • 118. HQL select Clause • Where Clause is used to limit the results returned from database. It can be used with aliases and if the aliases are not present in the Query, the properties can be referred by name. • String SQL_QUERY =" from Insurance as insurance where insurance.lngInsuranceId='1'"; Query query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate() ;it.hasNext();) • { Insurance insurance=(Insurance)it.next(); System.out.println("ID: " + insurance.getLngInsuranceId()); System.out.println("Name: " +insurance.getInsuranceName()); }
  • 119. The where clause • The where clause allows you to refine the list of instances returned. If no alias exists, you can refer to properties by name: – from Cat where name='Fritz' – from Cat as cat where cat.name='Fritz' • This returns instances of Cat named 'Fritz'. – select foo from Foo foo, Bar bar where foo.startDate = bar.date • returns all instances of Foo with an instance of bar with a date property equal to the startDate property of the Foo
  • 120. The order by clause • The list returned by a query can be ordered by any property of a returned class or components: • “from DomesticCat cat order by cat.name asc, cat.weight desc, cat.birthdate” • The optional asc or desc indicate ascending or descending order respectively.
  • 121. The group by clause • A query that returns aggregate values can be grouped by any property of a returned class or components: – select cat.color, sum(cat.weight), count(cat) from Cat cat group by cat.color . • A having clause is also allowed. – select cat.color, sum(cat.weight), count(cat) from Cat cat group by cat.color having cat.color in (eg.Color.TABBY, eg.Color.BLACK)
  • 122. HQL aggregate functions • Hibernate supports multiple aggregate functions. when they are used in HQL queries, they return an aggregate value (such as sum, average, and count) calculated from property values of all objects satisfying other query criteria. • These functions can be used along with the distinct and all options, to return aggregate values calculated from only distinct values and all values (except null values), respectively.
  • 123. HQL aggregate functions • Following is a list of aggregate functions with their respective syntax; all of them are selfexplanatory. count( [ distinct | all ] object | object.property ) count(*) (equivalent to count(all ...), counts null values also) sum ( [ distinct | all ] object.property) avg( [ distinct | all ] object.property) max( [ distinct | all ] object.property) min( [ distinct | all ] object.property)
  • 124. HQL aggregate functions • Example: “select cat.weight + sum(kitten.weight) from Cat cat join cat.kittens kitten group by cat.id, cat.weight “ select distinct cat.name from Cat cat select count(distinct product.supplier.name) from Product product
  • 125. Using Restrictions with HQL • As with SQL, you use the where clause to select results that match your query’s expressions. HQL provides many different expressions that you can use to construct a query. In the HQL language grammar, there are the following possible expressions: – Logic operators: OR, AND, NOT – Equality operators: =, <>, !=, ^= – Comparison operators: <, >, <=, >=, like, not like, between, not between
  • 126. Using Restrictions with HQL – Math operators: +, -, *, / – Concatenation operator: || – Cases: Case when <logical expression> then <unary expression> else _<unaryexpression> end – Collection expressions: some, exists, all, any • Example: – from Product where price > 25.0 and name like 'Mou%‘ – from DomesticCat cat where cat.name between 'A' and 'B' – from DomesticCat cat where cat.name in ( 'Foo', 'Bar', 'Baz' )
  • 127. Using Named Parameters • Hibernate supports named parameters in its HQL queries. This makes writing queries that accept input from the user easy—and you do not have to defend against SQL injection attacks. • SQL injection is an attack against applications that create SQL directly from user input with string concatenation. For instance, if we accept a name from the user through a web application form, then it would be very bad form to construct an SQL (or HQL) query like this: – String sql = "select p from products where name = '" + name + "'";
  • 128. Using Named Parameters • Hibernate’s named parameters are similar to the JDBC query parameters (?) you may already be familiar with, but Hibernate’s parameters are less confusing. It is also more straightforward to use Hibernate’s named parameters if you have a query that uses the same parameter in multiple places • The simplest example of named parameters uses regular SQL types for the parameters: String hql = "from Product where price > :price"; Query query = session.createQuery(hql); query.setDouble("price",25.0); List results = query.list();
  • 129. Using Named Parameters • When the value to be provided will be known only at run time, you can use some of HQL’s object-oriented features to provide objects as values for named parameters. The Query interface has a setEntity() method that takes the name of a parameter and an object. String supplierHQL = "from Supplier where name='MegaInc'"; Query supplierQuery = session.createQuery(supplierHQL); Supplier supplier = (Supplier) supplierQuery.list().get(0); String hql = "from Product as product where product.supplier=:supplier"; Query query = session.createQuery(hql); query.setEntity("supplier",supplier); List results = query.list()
  • 130. Named HQL Query in Mapping File
  • 131. Get Named HQL Query from Mapping File • Session session = HibernateUtil.currentSession(); Query query = session.getNamedQuery("HQLpricing"); List results = query.list(); displayObjectList(results); static public void displayObjectList(List list) { Iterator iter = list.iterator(); if (!iter.hasNext()) { System.out.println("No objects to display."); return; } while (iter.hasNext()) { System.out.println("New object"); Object obj = (Object) iter.next(); System.out.println(obj); }}
  • 132. Obtaining a Unique Result • HQL’s Query interface provides a uniqueResult() method for obtaining just one object from an HQL query. Query query = session.createQuery(hql); query.setMaxResults(1); Product product = (Product) query.uniqueResult(); //test for null here if needed
  • 133. Sorting Results with the order by Clause • To sort your HQL query’s results, you will need to use the order by clause. You can order the results by any property on the objects in the result set: either ascending (asc) or descending (desc). You can use ordering on more than one property in the query if you need to. A typical HQL query for sorting results looks like this: from Product p where p.price>25.0 order by p.price desc If you wanted to sort by more than one property, you would just add the additional properties to the end of the order by clause, separated by commas. For instance, you could sort by product price and the supplier’s name, as follows: from Product p order by p.supplier.name asc, p.price asc
  • 134. Using Multiple Table • Associations allow you to use more than one class in an HQL query, just as SQL allows you to use joins between tables in a relational database. Add an association to an HQL query with the join clause. • Hibernate supports five different types of joins: inner join, cross join, left outer join, right outer join, and full outer join. • If you use cross join, just specify both classes in the from clause (from Product p, Supplier s). • For the other joins, use a join clause after the from clause. Specify the type of join, the object property to join on, and an alias for the other class.
  • 135. Using Multiple Table • Example1: “select s.name, p.name, p.price from Product p inner join p.supplier as s” • Example2: “from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten “ • You may supply extra join conditions using the HQL with keyword. • Example 3: “from Cat as cat left join cat.kittens as kitten with kitten.bodyWeight > 10.0 “
  • 136. Demo • Down This Files To Get Demos