Hibernate
Hibernate
INTRODUCTION
Working with object-oriented software and a relational database is time consuming Need to bridge relational and object-oriented technologies, or to replace one with the other However the gap between the two is one of the hard facts Object-relational mapping tool is required to bridge this gap
What is ORM?
The term Object-Relational Mapping (ORM) refers to the technique of mapping a data representation, from an object model, to a relational data model with SQL-based schema
3
Hibernate Overview
Hibernate is a full-featured, open source Object-Relational mapping framework Hibernate is similar to EJB CMP/CMR (container-managedpersistence / container-managed-relationships) and JDO (Java Data Objects) Hibernate focuses entirely on OR mapping for relational databases and includes more features than most commercial products Hibernate helps in developing persistent classes following objectoriented idiom including: association, inheritance, polymorphism, composition, and collections Hibernate allows to express queries in its own portable SQL extension (HQL) As well as in native SQL, or with an object-oriented Criteria and Example API Hibernate is a Professional Open Source project
4
Hibernate Architecture
Session (net.sf.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.
ConnectionProvider (net.sf.hibernate.connection.ConnectionProvider)
(Optional) 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.
TransactionFactory (net.sf.hibernate.TransactionFactory)
(Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer.
11
Configuring Hibernate
Two types of Configurations:
Programmatic Configuration XML configuration
Programmatic Configuration
An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application's Java types to an SQL database. The Configuration is used to build an immutable SessionFactory. The mappings are compiled from various XML mapping files. 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.
12
Programmatic Configuration
Sample hibernate.properties file:
hibernate.connection.driver_class = oracle.jdbc.driver.OracleDriver hibernate.connection.url = jdbc:oracle:thin@localhost:1521:mydatabase hibernate.connection.username = myuser hibernate.connection.password = secret hibernate.dialect = net.sf.hibernate.dialect.Oracle9Dialect
Configuration cfg = new Configuration(); cfg.getProperties("hibernate.properties"); cfg.addResource("Customer.hbm.xml"); cfg.setProperty(Environment.SHOW_SQL, "true"); SessionFactory sessionFactory = = cfg.buildSessionFactory();
13
XML Configuration
An alternative approach to configuration - hibernate.cfg.xml. Used as a replacement for the hibernate.properties file or, if both are present, to override the properties. Configuration file is by default expected to be in the root of the CLASSPATH.
<?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.url">jdbc:oracle:thin@localhost:1521:mydatabase</property> <property name="connection.username">myuser</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="dialect">net.sf.hibernate.dialect.Oracle9Dialect</property> <property name="connection.password">secret</property> <property name="hibernate.show_sql">true</property> <!-- mapping files --> <mapping resource="Customer.hbm.xml" /> </session-factory> </hibernate-configuration>
14
XML Configuration
Loading of the XML configuration
Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory sessionFactory = = cfg.buildSessionFactory();
15
17
20
Mapping type
integer long short float double big_decimal character string byte boolean yes_no true_false
Java type
int or java.lang.Integer long or java.lang.Long short or java.lang.Short float or java.lang.Float double or java.lang.Double java.math.BigDecimal java.lang.String java.lang.String byte or java.lang.Byte boolean or java.lang.Boolean boolean or java.lang.Boolean boolean or java.lang.Boolean
23
24
The <key-property> tag specifies the set of columns which makes the composite key.
25
Storing Data:
Customer customerObj = new Customer(); customerObj.setCustomerId(id); customerObj.setBirthDate(date); customerObj.setName(Shiv); Session session = sessionFactory.getSession(); Transaction transaction = session.beginTansaction(); session.save(customerObj); transaction.commit();
26
Lect_id
Lect_subj
Stud_id Stud_name Lect_id
28
The <Key> tag here represents the column in the Lecturer class which is a foreign key for the Student class. i.e. the key with which the two classes are linked. The <one-to-many> tag specifies the class with which the mapping is to be done and the foreign key column in the class.
29
32
33
35
36
Note: The person table would have the columns pid, birthday, initial, first and last.
37
<set name="someNames" table="some_names" lazy="true"> <key column="id"/> <composite-element class="eg.Name"> <!-- class attribute required --> <property name="initial"/> <property name="first"/> <property name="last"/> </composite-element> </set>
38
There are three basic inheritance mapping strategies: Table per class hierarchy Table per subclass Table per concrete class
40
41
43
The table attribute of the element signifies the table to which these subclasses are mapped. And the key tag specifies the foreign key of the subclass.
For instance, in the above example, the attributes specific to the CreditCardPayment subclass is mapped to the CREDIT_PAYMENT table. The PAYMENT_ID column is the foreign key which joins the subclasses to the parent class. The <property> tag specifies the attributes of the respective tables.
44
The mapping is done by using <union-subclass> element. All the subclasses have a common primary key.
The table attribute of the element signifies the table to which these subclasses are mapped. For instance, in the above example, the attributes specific to the CreditCardPayment subclass is mapped to the CREDIT_PAYMENT table. The PAYMENT_ID column is the primary key of all the subclasses. The <property> tag specifies the attributes of the respective tables.
46
from Employee
Returns all Employee rows from data base in the form of Employee class objects which is mapped to the table Employee
Clauses :Select (Optional) from (Required except with Session and Filter) where ( Optional) Other : Order By, Group By, Having
48
49
Polymorphic
HQL queries are polymorphic due to inheritance mapping. from Employee Will return the instances not only of Employee but also all the subclasses of Employee. HQL polymorphic queries will return instances of all the persistence classes that extend the class or implement the interface.
52
Criteria Queries
HQL has criteria queries to perform operations like narrowing the result set object which are returned based on the criteria defined at runtime. Interface org.hibernate.Criteria represents query against a particular class.
54
Example Queries
Example example = Example.create(cat) .excludeZeroes() //exclude zero valued properties .excludeProperty("color") //exclude the property named "color" .ignoreCase() //perform case insensitive string comparisons .enableLike(); //use like for string comparisons
56
Native SQL
Hibernate allows developers to write complex queries in the SQL format itself using native SQL interface, retaining the advantages of persistence. Query sqlQuery = sess.createSQLQuery("select {cat.*} from cats {cat}", "cat", Cat.class); sqlQuery.setMaxResults(50); List cats = sqlQuery.list(); List queryList = session.createSQLQuery(select * from Employee).addEntity(Employee.class).list(); addEntity() will do the necessary mapping of Employee table to Employee class which results in returning generic objects.
57
Native SQL
String sql = "select cat.originalId as {cat.id}, " + " cat.mateid as {cat.mate}, cat.sex as {cat.sex}, + " cat.weight*10 as {cat.weight}, cat.name as {cat.name}" + " from cat_log cat where {cat.mate} = :catId" List loggedCats = sess.createSQLQuery(sql, "cat", Cat.class) . setLong("catId", catId) .list();
58
Hibernate Filters
Hibernate filter is a global named parameterized filter that may be enabled or disabled for a particular hibernate session. In order to use filters they must be defined and attached to appropriate mapping elements. To define a filter use <filter-def> element within <hibernate-mapping/> element. Filters can be enabled or disabled at session level.
60
61
public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static final ThreadLocal session = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session s = (Session) session.get(); // Open a new Session, if this Thread has none yet if (s == null) { s = sessionFactory.openSession(); session.set(s); } return s; } public static void closeSession() throws HibernateException { Session s = (Session) session.get(); session.set(null); if (s != null) s.close(); } }
62
Object States
63
66
References
Websites:
http://www.hibernate.org http://hibernate.bluemars.net/hib_docs/referen ce/en/html/index.html
Books:
Hibernate Reference Document Version: 3.0.5 Hibernate in Action - By Christian Bauer and Galvin King
67