Hibernate Hibernate Hibernate Framework Hibernate is a Java

Hibernate

Hibernate • Hibernate Framework • Hibernate is a Java framework that simplifies the development of Java application to interact with the database. • It is an open source, lightweight, ORM (Object Relational Mapping) tool. • Hibernate implements the specifications of JPA (Java Persistence API) for data persistence.

Hibernate • ORM Tool • An ORM tool simplifies the data creation, data manipulation and data access. It is a programming technique that maps the object to the data stored in the database.

Hibernate • Advantages of Hibernate Framework 1) Open Source and Lightweight – Hibernate framework is open source under the LGPL license and lightweight. 2) Fast Performance – The performance of hibernate framework is fast because cache is internally used in hibernate framework. There are two types of cache in hibernate framework first level cache and second level cache. First level cache is enabled by default.

Hibernate 3) Database Independent Query – HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the database independent queries. So you don't need to write database specific queries. Before Hibernate, if database is changed for the project, we need to change the SQL query as well that leads to the maintenance problem. 4) Automatic Table Creation – Hibernate framework provides the facility to create the tables of the database automatically. So there is no need to create tables in the database manually. 5) Simplifies Complex Join – Fetching data from multiple tables is easy in hibernate framework. 6) Provides Query Statistics and Database Status – Hibernate supports Query cache and provide statistics about query and database status.

Hibernate • The Hibernate architecture includes many objects such as persistent object, session factory, transaction factory, connection factory, session, transaction etc. • The Hibernate architecture is categorized in four layers. • Java application layer • Hibernate framework layer • Backhand api layer • Database layer

Hibernate

Hibernate

Hibernate • Hibernate framework uses many objects such as session factory, session, transaction etc. along with existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction API) and JNDI (Java Naming Directory Interface).

Hibernate • For creating the first hibernate application, we must know the elements of Hibernate architecture. They are as follows: • Session. Factory • Session • Transaction • Connection. Provider • Transaction. Factory

Hibernate • The Session. Factory is a factory of session and client of Connection. Provider. It holds second level cache (optional) of data. The org. hibernate. Session. Factory interface provides factory method to get the object of Session. • The session object provides an interface between the application and data stored in the database. It is a shortlived object and wraps the JDBC connection. It is factory of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The org. hibernate. Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria.

Hibernate • Transaction • The transaction object specifies the atomic unit of work. It is optional. The org. hibernate. Transaction interface provides methods for transaction management. • Connection. Provider • It is a factory of JDBC connections. It abstracts the application from Driver. Manager or Data. Source. It is optional. • Transaction. Factory • It is a factory of Transaction. It is optional.

Hibernate • Here, we are going to create a simple example of hibernate application using eclipse IDE. For creating the first hibernate application in Eclipse IDE, we need to follow the following steps: • • Create the java project Add jar files for hibernate Create the Persistent class Create the mapping file for Persistent class Create the Configuration file Create the class that retrieves or stores the persistent object Run the application

Hibernate 1) Create the java project • Create the java project by File Menu - New - project - java project. Now specify the project name then next - finish. 2) Add jar files for hibernate • To add the jar files Right click on your project - Build path - Add external archives. Now select all the jar files as shown in the image given below then click open.

Hibernate

Hibernate • Create a persistent class • This is the Java class which holds objects from the database • Usually it corresponds to one entry in the database table • If we have Employee data inside database, we should create Employee. java class.

Hibernate • A simple Persistent class should follow some rules: • A no-arg constructor: It is recommended that you have a default constructor at least package visibility so that hibernate can create the instance of the Persistent class by new. Instance() method. • Provide an identifier property: It is better to assign an attribute as id. This attribute behaves as a primary key in database. • Declare getter and setter methods: The Hibernate recognizes the method by getter and setter method names by default. • Prefer non-final class: Hibernate uses the concept of proxies, that depends on the persistent class. The application programmer will not be able to use proxies for lazy association fetching.

public class Employee { private int id; private String first. Name, last. Name; public int get. Id() { return id; } public void set. Id(int id) { this. id = id; } public String get. First. Name() { return first. Name; } public void set. First. Name(String first. Name) { this. first. Name = first. Name; } public String get. Last. Name() { return last. Name; } public void set. Last. Name(String last. Name) { this. last. Name = last. Name; }

Hibernate • Now create the mapping file for Persistent class • To create the mapping file, Right click on src - new - file - specify the file name (e. g. employee. hbm. xml) - ok. It must be outside the package.

Hibernate • The mapping file name conventionally, should be class_name. hbm. xml. There are many elements of the mapping file. • hibernate-mapping : It is the root element in the mapping file that contains all the mapping elements. • class : It is the sub-element of the hibernate-mapping element. It specifies the Persistent class. • id : It is the subelement of class. It specifies the primary key attribute in the class. • generator : It is the sub-element of id. It is used to generate the primary key. There are many generator classes such as assigned, increment, hilo, sequence, native etc. We will learn all the generator classes later. • property : It is the sub-element of class that specifies the property name of the Persistent class.

Hibernate • employee. hbm. xml <? xml version='1. 0' encoding='UTF-8'? > <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate Mapping DTD 5. 3//EN" "http: //hibernate. sourceforge. net/hibernate-mapping-5. 3. dtd"> <hibernate-mapping> <class name="com. engineering. hibernate. Employee" table="emp 1000"> <id name="id"> <generator class="assigned"></generator> </id> <property name="first. Name"></property> <property name="last. Name"></property> </class> </hibernate-mapping>

Hibernate • Create the Configuration file • The configuration file contains all the informations for the database such as connection_url, driver_class, username, password etc. The hbm 2 ddl. auto property is used to create the table in the database automatically. • We will have in-depth learning about Dialect class in next topics. • To create the configuration file, right click on src - new file. • Now specify the configuration file name e. g. hibernate. cfg. xml.

Hibernate

• Create the test class that retrieves or stores the persistent object • In this class, we are simply storing the employee object to the database. public static void main( String[] args ) { Standard. Service. Registry ssr = new Standard. Service. Registry. Builder(). configure("hibernate. cfg. xml"). build(); Metadata meta = new Metadata. Sources(ssr). get. Metadata. Builder(). build(); Session. Factory factory = meta. get. Session. Factory. Builder(). build(); Session session = factory. open. Session(); Transaction t = session. begin. Transaction(); Employee e 1=new Employee(); e 1. set. Id(1); e 1. set. First. Name(“Petar"); e 1. set. Last. Name(“Petrovic"); session. save(e 1); t. commit(); System. out. println("successfully saved"); factory. close(); session. close(); }

Hibernate • Hibernate Example using Annotation in Eclipse • The hibernate application can be created with annotation. There are many annotations that can be used to create hibernate application such as @Entity, @Id, @Table etc. • Hibernate Annotations are based on the JPA 2 specification and supports all the features. • All the JPA annotations are defined in the javax. persistence package. Hibernate Entity. Manager implements the interfaces and life cycle defined by the JPA specification.

Hibernate • The core advantage of using hibernate annotation is that you don't need to create mapping (hbm) file. • Here, hibernate annotations are used to provide the meta data.

Hibernate • Example to create the hibernate application with Annotation • Here, we are going to create a maven based hibernate application using annotation in eclipse IDE. For creating the hibernate application in Eclipse IDE, we need to follow the below steps: • 1) Create the Maven Project • To create the maven project left click on File Menu - New- Maven Project.

Hibernate

Hibernate

Hibernate

Hibernate • Open pom. xml file and click source. • Now, add the below dependencies between <dependencies>. . </dependencies> tag. • These dependencies are used to add the jar files in Maven project.

Hibernate

Hibernate • Due to certain license issues, Oracle drivers are not present in public Maven repository. • We can install it manually. To install Oracle driver into your local Maven repository, follow the following steps: • Install Maven • Run the command : install-file Dfile=Path/to/your/ojdbc 14. jar Dgroup. Id=com. oracle -Dartifact. Id=ojdbc 14 Dversion=12. 1. 0 -Dpackaging=jar

Hibernate • Create the Persistence class. • Here, we are creating the same persistent class which we have created in the previous topic. But here, we are using annotation. • @Entity annotation marks this class as an entity. • @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default. • @Id annotation marks the identifier for this entity. • @Column annotation specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name by default.

Hibernate import javax. persistence. Entity; import javax. persistence. Id; import javax. persistence. Table; @Entity @Table(name= "employees") public class Employee { @Id private int id; private String first. Name, last. Name; …

Hibernate • Create the Configuration file • To create the configuration file, right click on src/main/java - new - file - specify the file name (e. g. hibernate. cfg. xml) - Finish.

Hibernate

Hibernate • Generator classes • The <generator> class is a sub-element of id. It is used to generate the unique identifier for the objects of persistent class. There are many generator classes defined in the Hibernate Framework. • All the generator classes implements the org. hibernate. id. Identifier. Generator interface

Hibernate • Hibernate framework provides many built-in generator classes: – – – assigned increment sequence hilo native identity seqhilo uuid guid select foreign sequence-identity

Hibernate • assigned • It is the default generator strategy if there is no <generator> element. In this case, application assigns the id. For example:

Hibernate • increment • It generates the unique id only if no other process is inserting data into this table. It generates short, int or long type identifier. If a table contains an identifier then the application considers its maximum value else the application consider that the first generated identifier is 1. For each attribute value, the hibernate increment the identifier by 1. Syntax:

Hibernate • native • It uses identity, sequence or hilo depending on the database vendor. • identity • It is used in Sybase, My SQL, MS SQL Server, DB 2 and Hypersonic. SQL to support the id column. The returned id is of type short, int or long. It is responsibility of database to generate unique identifier. • seqhilo • It uses high and low algorithm on the specified sequence name. The returned id is of type short, int or long.

Hibernate • SQL Dialects in Hibernate • The dialect specifies the type of database used in hibernate so that hibernate generate appropriate type of SQL statements. For connecting any hibernate application with the database, it is required to provide the configuration of SQL dialect. • Syntax of SQL Dialect: • <property name="dialect">org. hibernate. dialect. Oracle 9 Dialect</property>

Hibernate • There are many Dialects classes defined for RDBMS in the org. hibernate. dialect package. • There are numerous classes, but most commonly used are shown in the next slide

Hibernate

Hibernate • Transaction management • A transaction simply represents a unit of work. In such case, if one step fails, the whole transaction fails (which is termed as atomicity). A transaction can be described by ACID properties (Atomicity, Consistency, Isolation and Durability).

Hibernate

Hibernate • In hibernate framework, we have Transaction interface that defines the unit of work. It maintains abstraction from the transaction implementation (JTA, JDBC). • A transaction is associated with Session and instantiated by calling session. begin. Transaction().

Hibernate • The methods of Transaction interface are as follows: • void begin() starts a new transaction. • void commit() ends the unit of work unless we are in Flush. Mode. NEVER. • void rollback() forces this transaction to rollback. • void set. Timeout(int seconds) it sets a transaction timeout for any transaction started by a subsequent call to begin on this instance. • boolean is. Alive() checks if the transaction is still alive. • void register. Synchronization(Synchronization s) registers a user synchronization callback for this transaction. • boolean was. Commited() checks if the transaction is commited successfully. • boolean was. Rolled. Back() checks if the transaction is rolledback successfully.

Hibernate

Hibernate • Session • The main runtime interface between a Java application and Hibernate. This is the central API class abstracting the notion of a persistence service. • The lifecycle of a Session is bounded by the beginning and end of a logical transaction. (Long transactions might span several database transactions. ) • The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes.

Hibernate • Instances may exist in one of three states: • transient: never persistent, not associated with any Session • persistent: associated with a unique Session • detached: previously persistent, not associated with any Session

Hibernate • Transient instances may be made persistent by calling save(), persist() or save. Or. Update(). • Persistent instances may be made transient by calling delete(). • Any instance returned by a get() or load() method is persistent. • Detached instances may be made persistent by calling update(), save. Or. Update(), lock() or replicate(). • The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

Hibernate • save() and persist() result in an SQL INSERT, delete() in an SQL DELETE and update() or merge() in an SQL UPDATE. Changes to persistent instances are detected at flush time and also result in an SQL UPDATE. save. Or. Update() and replicate() result in either an INSERT or an UPDATE. • It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a Session. Factory.

Hibernate • A typical transaction should use the following idiom:

Hibernate • If the Session throws an exception, the transaction must be rolled back and the session discarded. • The internal state of the Session might not be consistent with the database after the exception occurs.

Hibernate • Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't depends on the table of the database. • Instead of table name, we use class name in HQL. So it is database independent query language.

Hibernate • There are many advantages of HQL. They are as follows: – database independent – supports polymorphic queries – easy to learn for Java Programmer • Query Interface • It is an object oriented representation of Hibernate Query. The object of Query can be obtained by calling the create. Query() method Session interface.

Hibernate • The query interface provides many methods. There is given commonly used methods: – public int execute. Update() is used to execute the update or delete query. – public List list() returns the result of the ralation as a list. – public Query set. First. Result(int rowno) specifies the row number from where record will be retrieved. – public Query set. Max. Result(int rowno) specifies the no. of records to be retrieved from the relation (table). – public Query set. Parameter(int position, Object value) it sets the value to the JDBC style query parameter. – public Query set. Parameter(String name, Object value) it sets the value to a named query parameter.

Hibernate • Example of HQL to get all the records Query query=session. create. Query("from Employee"); //here persistent class name is Employee List list = query. list(); • Example of HQL to get records with pagination Query query=session. create. Query("from Employee"); query. set. First. Result(5); query. set. Max. Result(10); List list=query. list(); //will return the records from 5 to 10 th number

Hibernate • Example of HQL update query Transaction tx=session. begin. Transaction(); Query q=session. create. Query("update User set name=: n where id=: i"); q. set. Parameter("n", “Petar Petrovic"); q. set. Parameter("i", 111); int status=q. execute. Update(); System. out. println(status); tx. commit();

Hibernate • Example of HQL delete query Query query=session. create. Query("delete from Employee where id=100"); //specifying class name (Employee) not tablename query. execute. Update();

Hibernate • HQL with Aggregate functions • You may call avg(), min(), max() etc. aggregate functions by HQL. Let's see some common examples • Example to get total salary of all the employees Query q=session. create. Query("select sum(salary) from Employee"); List<Integer> list=q. list(); System. out. println(list. get(0)); • Example to get maximum salary of employee Query q=session. create. Query("select max(salary) from Employee");

Hibernate • HCQL (Hibernate Criteria Query Language) • The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the specific criteria. • The Criteria interface provides methods to apply criteria such as retrieving all the records of table whose salary is greater than 50000 etc.

Hibernate • Advantage of HCQL • The HCQL provides methods to add criteria, so it is easy for the Java programmer to add criteria. The Java programmer is able to add many criteria on a query. • Criteria Interface • The Criteria interface provides many methods to specify criteria. The object of Criteria can be obtained by calling the create. Criteria() method of Session interface.

Hibernate • Syntax of create. Criteria() method of Session interface public Criteria create. Criteria(Class c) • • The commonly used methods of Criteria interface are as follows: public Criteria add(Criterion c) is used to add restrictions. public Criteria add. Order(Order o) specifies ordering. public Criteria set. First. Result(int first. Result) specifies the first number of record to be retreived. • public Criteria set. Max. Result(int total. Result) specifies the total number of records to be retreived. • public List list() returns list containing object. • public Criteria set. Projection(Projection projection) specifies the projection.

Hibernate • • • Restrictions class provides methods that can be used as Criterion. The commonly used methods of Restrictions class are as follows: public static Simple. Expression lt(String property. Name, Object value) sets the less than constraint to the given property. public static Simple. Expression le(String property. Name, Object value) sets the less than or equal constraint to the given property. public static Simple. Expression gt(String property. Name, Object value) sets the greater than constraint to the given property. public static Simple. Expression ge(String property. Name, Object value) sets the greater than or equal than constraint to the given property. public static Simple. Expression ne(String property. Name, Object value) sets the not equal constraint to the given property. public static Simple. Expression eq(String property. Name, Object value) sets the equal constraint to the given property. public static Criterion between(String property. Name, Object low, Object high) sets the between constraint. public static Simple. Expression like(String property. Name, Object value) sets the like constraint to the given property.

Hibernate • The Order class represents an order. The commonly used methods of Restrictions class are as follows: • public static Order asc(String property. Name) applies the ascending order on the basis of given property. • public static Order desc(String property. Name) applies the descending order on the basis of given property.

Hibernate • Example of HCQL to get all the records Crietria c =session. create. Criteria(Employee. class); //passing Class class argument List list=c. list(); • Example of HCQL to get the 10 th to 20 th record Crietria c =session. create. Criteria(Employee. class); c. set. First. Result(10); c. set. Max. Result(20); List list=c. list();

Hibernate • Example of HCQL to get the records whose salary is greater than 10000 Crietria c=session. create. Criteria(Emp. class); c. add(Restrictions. gt("salary", 10000)); //salary is the propertyname List list=c. list(); • Example of HCQL to get the records in ascending order on the basis of salary Crietria c=session. create. Criteria(Emp. class); c. add. Order(Order. asc("salary")); List list=c. list();

Hibernate • HCQL with Projection • We can fetch data of a particular column by projection such as name etc. Let's see the simple example of projection that prints data of NAME column of the table only. Criteria c=session. create. Criteria(Employee. class); c. set. Projection(Projections. property("name")); List list=c. list();

Hibernate • The hibernate named query is way to use any query by some meaningful name. • It is like using alias names. • The Hibernate framework provides the concept of named queries so that application programmer need not to scatter queries to all the java code. • There are two ways to define the named query in hibernate: – by annotation – by mapping file.

Hibernate • Hibernate Named Query by annotation • If you want to use named query in hibernate, you need to have knowledge of @Named. Queries and @Named. Query annotations. • @Name. Queries annotation is used to define the multiple named queries. • @Name. Query annotation is used to define the single named query.

Hibernate

Hibernate

Hibernate • Using named query: Session. Factory factory=meta. get. Session. Factory. Builder(). build(); Session session=factory. open. Session(); //Hibernate Named Query Typed. Query query = session. get. Named. Query("find. Employee. By. Name"); query. set. Parameter("name", “Petar"); List<Employee> employees=query. get. Result. List(); Iterator<Employee> itr=employees. iterator(); while(itr. has. Next()){ Employee e=itr. next(); System. out. println(e); } session. close();

Hibernate • Caching in Hibernate • Hibernate caching improves the performance of the application by pooling the object in the cache. It is useful when we have to fetch the same data multiple times. • There are mainly two types of caching: • First Level Cache, and • Second Level Cache

Hibernate • First Level Cache • Session object holds the first level cache data. It is enabled by default. The first level cache data will not be available to entire application. An application can use many session object.

Hibernate • Second Level Cache uses a common cache for all the session object of a session factory. It is useful if you have multiple session objects from a session factory. • Session. Factory object holds the second level cache data. The data stored in the second level cache will be available to entire application. But we need to enable it explicitely. • Different vendors have provided the implementation of Second Level Cache. • EH (Easy Hibernate) Cache • Swarm Cache • OS Cache • JBoss Cache

Hibernate • Each implementation provides different cache usage functionality. There are four ways to use second level cache. • read-only: caching will work for read only operation. • nonstrict-read-write: caching will work for read and write but one at a time. • read-write: caching will work for read and write, can be used simultaneously. • transactional: caching will work for transaction.

Hibernate • The cache-usage property can be applied to class or collection level in hbm. xml file. The example to define cache usage is given below: <cache usage="read-only" />

Hibernate <dependency> <group. Id>org. hibernate</group. Id> <artifact. Id>hibernate-core</artifact. Id> <version>5. 2. 16. Final</version> </dependency> <group. Id>com. oracle</group. Id> <artifact. Id>ojdbc 14</artifact. Id> <version>10. 2. 0. 4. 0</version> </dependency> <group. Id>net. sf. ehcache</group. Id> <artifact. Id>ehcache</artifact. Id> <version>2. 10. 3</version> </dependency> <group. Id>org. hibernate</group. Id> <artifact. Id>hibernate-ehcache</artifact. Id> <version>5. 2. 16. Final</version> </dependency>

Hibernate • Config file <hibernate-configuration> <session-factory> <property name="show_sql">true</property> <property name="hbm 2 ddl. auto">update</property> <property name="dialect">org. hibernate. dialect. Oracle 9 Dialect</property> <property name="connection. url">jdbc: oracle: thin: @localhost: 1521: xe</property> <property name="connection. username">system</property> <property name="connection. password">jtp</property> <property name="connection. driver_class">oracle. jdbc. driver. Oracle. Driver</property> <property name="cache. use_second_level_cache">true</property> <property name="cache. region. factory_class">org. hibernate. cache. ehcache. Eh. Cache. Region. Factor y</property> <mapping class="com. engineering. Employee"/> </session-factory> </hibernate-configuration>

Hibernate Session. Factory factory=meta. get. Session. Factory. Builder(). build(); Session session 1=factory. open. Session(); Employee emp 1=(Employee)session 1. load(Employee. class, 121); System. out. println(emp 1. get. Id()+" "+emp 1. get. Name()+" "+emp 1. get. Salary()); session 1. close(); Session session 2=factory. open. Session(); Employee emp 2=(Employee)session 2. load(Employee. class, 121); System. out. println(emp 2. get. Id()+" "+emp 2. get. Name()+" "+emp 2. get. Salary()); session 2. close();

Hibernate • As we can see here, hibernate does not fire query twice. If you don't use second level cache, hibernate will fire query twice because both query uses different session objects.

Hibernate • Lazy vs eager loading • When working with an ORM, data fetching/loading can be classified into two types: eager and lazy. • We are going to point out differences and show those can be used in Hibernate.

Hibernate • The first thing that we should discuss here is what lazy loading and eager loading are: • Eager Loading is a design pattern in which data initialization occurs on the spot • Lazy Loading is a design pattern which is used to defer initialization of an object as long as it's possible • Let's see how this actually works with some examples

Hibernate

Hibernate

Hibernate • One User can have multiple Order. Details. In eager loading strategy, if we load the User data, it will also load up all orders associated with it and will store it in a memory. • But, when lazy loading is enabled, if we pull up a User. Lazy, Order. Detail data won't be initialized and loaded into a memory until an explicit call is made to it.

Hibernate • The default behavior is to load ‘property values eagerly’ and to load ‘collections lazily’. Contrary to what you might remember if you have used plain Hibernate 2 (mapping files) before, where all references (including collections) are loaded eagerly by default. • Also note that @One. To. Many and @Many. To. Many associations are defaulted to LAZY loading; and @One. To. One and @Many. To. One are defaulted to EAGER loading. This is important to remember to avoid any pitfall in future.

Hibernate • To enable lazy loading explicitly you must use “fetch = Fetch. Type. LAZY” on a association which you want to lazy load when you are using hibernate annotations. • A hibernate lazy load example will look like this: @One. To. Many( mapped. By = "category", fetch = Fetch. Type. LAZY ) private Set<Product. Entity> products;

Hibernate • • • Lazy Loading Advantages: Initial load time much smaller than in the other approach Less memory consumption than in the other approach Disadvantages: Delayed initialization might impact performance during unwanted moments • In some cases you need to handle lazily-initialized objects with a special care or you might end up with an exception

Hibernate • Eager Loading: • Advantages: • No delayed initialization related performance impacts • Disadvantages: • Long initial loading time • Loading too much unnecessary data might impact performance
- Slides: 94