Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data...

38
Hibernate 4.3

description

Hibernate Advantages: 1.Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code. 2.Provides simple APIs for storing and retrieving Java objects directly to and from the database. 3.If there is change in Database or in any table then the only need to change XML file properties. 4.Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects. 5.Hibernate does not require an application server to operate. 6.Manipulates Complex associations of objects of your database. 7.Minimize database access with smart fetching strategies. 8.Provides Simple querying of data.

Transcript of Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data...

Page 1: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Hibernate 4.3

Page 2: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence related programming tasks.Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns..

Page 3: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Hibernate Advantages:1. Hibernate takes care of mapping Java classes to database

tables using XML files and without writing any line of code.2. Provides simple APIs for storing and retrieving Java objects

directly to and from the database.3. If there is change in Database or in any table then the only

need to change XML file properties.4. Abstract away the unfamiliar SQL types and provide us to

work around familiar Java Objects.5. Hibernate does not require an application server to operate.6. Manipulates Complex associations of objects of your

database.7. Minimize database access with smart fetching strategies.8. Provides Simple querying of data.

Page 4: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java.. S.N. Advantages

1 Lets business code access objects rather than DB tables.

2 Hides details of SQL queries from OO logic.

3 Based on JDBC 'under the hood'

4 No need to deal with the database implementation.

5 Entities based on business concepts rather than database structure.

6 Transaction management and automatic key generation.

7 Fast development of application.

8 Cache Management

9 Automatic creation of required tables in database

Page 5: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Hibernate Query Language (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 queries are translated by Hibernate into conventional SQL queries which in turns perform action on database.

Page 6: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

FROM ClauseUse FROM clause if you want to load a complete persistent objects into memory. Following is the simple syntax of using FROM clause:

String hql = "FROM Employee"; Query query = session.createQuery(hql);

List results = query.list();

Page 7: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

SELECT ClauseSELECT clause provides more control over the result set than the from clause. If you want to

obtain few properties of objects instead of the complete object, use the SELECT clause.

String hql = "SELECT E.firstName FROM Employee E";

Query query = session.createQuery(hql); List results = query.list();

Page 8: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

AS Clause…The AS clause can be used to assign aliases

to the classes in your HQL queries, specially when you have long queries. For

instance, our previous simple example would be the following:

String hql = "FROM Employee AS E"; Query query = session.createQuery(hql);

List results = query.list();

Page 9: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

WHERE Clause…to narrow the specific objects that are returned from storage, you can use the

WHERE clause.:String hql = "FROM Employee E WHERE

E.id = 10"; Query query = session.createQuery(hql);

List results = query.list();

Page 10: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

ORDER BY ClauseTo sort 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). String hql = "FROM Employee E WHERE E.id >

10 ORDER BY E.salary DESC"; Query query = session.createQuery(hql);

List results = query.list();

Page 11: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

GROUP BY ClauseThis clause lets Hibernate pull information from the database and group it based on a value of

an attribute and, typically, use the result to include an aggregate value. Following is the

simple syntax of using GROUP BY clause:String hql = "SELECT SUM(E.salary), E.firtName

FROM Employee E " + "GROUP BY E.firstName"; Query query = session.createQuery(hql);

List results = query.list();

Page 12: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

UPDATE ClauseUPDATE clause can be used to update one or more

properties of an one or more objects

String hql = "UPDATE Employee set salary = :salary " + "WHERE id = :employee_id"; Query query = session.createQuery(hql); query.setParameter("salary", 1000); query.setParameter("employee_id", 10); int result = query.executeUpdate(); System.out.println("Rows affected: " + result);

Page 13: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

DELETE ClauseString hql = "DELETE FROM Employee " + "WHERE id = :employee_id"; Query query = session.createQuery(hql); query.setParameter("employee_id", 10); int result = query.executeUpdate(); System.out.println("Rows affected: " + result);

INSERT ClauseString hql = "INSERT INTO Employee(firstName, lastName, salary)" + "SELECT firstName, lastName, salary FROM old_employee"; Query query = session.createQuery(hql); int result = query.executeUpdate(); System.out.println("Rows affected: " + result);

Page 14: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

PaginationString hql = "FROM Employee";

Query query = session.createQuery(hql); query.setFirstResult(1); query.setMaxResults(10); List results = query.list();

Below are other values for hbm2ddl.auto1. validate: validate the schema, makes no changes to the

database.2. update: update the schema.3. create: creates the schema, destroying previous data.4. create-drop: drop the schema at the end of the session.

Page 15: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Hibernate Lifecycle Of pojo Class Objects Hibernate considers objects it can manage to always be in one of four states – Transient – Persistent – Removed – Detached

Objects transition from state to state through various method calls.Transient State

All objects start off in the transientstate– 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

Page 16: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Persistent State

Hibernate is aware of, and managing, the object Has a database idAlready existing object retrieved from the databaseFormerly transient object about to be saved

This is the only state where objects are saved to the databaseModifications made in other states are NOT saved to the database while the object remains in that stateChanges to objects in a persistent state are automatically saved to the database without invoking session persistence methods

Objects are made persistent through calls against the Hibernate session– session.save(account); – session.lock(account);– session.update(account); – session.merge(account);

Session session = SessionFactory.getCurrentSession();// ‘transient’ state – Hibernate is NOT aware that it existsAccount account = new Account();// transition to the ‘persistent’ state. Hibernate is NOW// aware of the object and will save it to the databasesession.saveOrUpdate(account);// modification of the object will automatically be// saved because the object is in the ‘persistent’ stateaccount.setBalance(500);// commit the transactionsession.getTransaction().commit();

Page 17: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

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 tothe database– Picked up for garbage collection once it falls outof scope • Hibernate does not null-out the in-memory object

Session session = SessionFactory.getCurrentSession();// retrieve account with id 1. account is returned in a ‘persistent’ stateAccount account = session.get(Account.class, 1);// transition to the ‘removed’ state. Hibernate deletes the// database record, and no longer manages the objectsession.delete(account);// modification is ignored by Hibernate since it is in the ‘removed’ stateaccount.setBalance(500);// commit the transactionsession.getTransaction().commit();// notice the Java object is still alive, though deleted from the database.// stays alive until developer sets to null, or goes out of scopeaccount.setBalance(1000);

Page 18: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Detached State

A persistent object that is still referenced after closure of the active session– session.close() changes object’s state from persisted to detachedStill represents a valid row in the databaseNo longer managed by Hibernate

Changes made to detached objects are not saved to the database while object remains in the detached stateCan be reattached, returning it to the persistent state and causing it to save its state to the database

update(); merge();lock(); // reattaches, but does not save state

Session session1 = SessionFactory.getCurrentSession();// retrieve account with id 1. account is returned in a ‘persistent’ stateAccount account = session1.get(Account.class, 1);// transition to the ‘detached’ state. Hibernate no longer manages the objectsession1.close();// modification is ignored by Hibernate since it is in the ‘detached’// state, but the account still represents a row in the databaseaccount.setBalance(500);// re-attach the object to an open session, returning it to the ‘persistent’// state and allowing its changes to be saved to the databaseSession session2 = SessionFactory.getCurrentSession();session2.update(account);// commit the transactionsession2.getTransaction().commit();

Page 19: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

HQL Aggregate Methods1.avg(property name)The average of a property's value2.count(property name or *)The number of times a property occurs in the results3.max(property name)The maximum value of the property values4.min(property name)The minimum value of the property values5.sum(property name)The sum total of the property values

Query q=session.createQuery("select max(salary) from Emp");

Page 20: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

entire concept of Hibernate is to take the values from Java class attributes and persist them to a database table. A mapping document helps Hibernate in determining how to pull the values from the classes and map them with table and associated fields.Hibernate works best if these persistent classes follow some simple rules, also known as the Plain Old Java Object (POJO).

Page 21: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

1. All Java classes that need to be persisted need a default constructor.

2. All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table.

3. All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style.

4. A central feature of Hibernate, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods.

5. All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework.

Page 22: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); // do some work ... tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); }If the Session throws an exception, the transaction must be rolled back and the session must be discarded.

Page 23: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Hibernate Mapping TypesWhen preparing a Hibernate mapping document, we have seen that you map Java data types into RDBMS data types. The types declared and used in the mapping files are not Java data types; they are not SQL database types either. These types are called Hibernate mapping types, which can translate from Java to SQL data types and vice versa.

Page 24: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Mapping type Java type ANSI SQL Type

integer int or java.lang.Integer INTEGER

long long or java.lang.Long BIGINT

short short or java.lang.Short SMALLINT

float float or java.lang.Float FLOAT

double double or java.lang.Double DOUBLE

big_decimal java.math.BigDecimal NUMERIC

character java.lang.String CHAR(1)

string java.lang.String VARCHAR

byte byte or java.lang.Byte TINYINT

boolean boolean or java.lang.Boolean BIT

yes/no boolean or java.lang.Boolean CHAR(1) ('Y' or 'N')

true/false boolean or java.lang.Boolean CHAR(1) ('T' or 'F')

Page 25: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Mapping type

Java type ANSI SQL Type

date java.util.Date or java.sql.Date DATE

time java.util.Date or java.sql.Time TIME

timestamp java.util.Date or java.sql.Timestamp

TIMESTAMP

calendar java.util.Calendar TIMESTAMP

calendar_date

java.util.Calendar DATE

Page 26: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Hibernate Criteria APIHibernate also provides Criteria API which allows to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.//below, returns every object of Employee classCriteria cr = session.createCriteria(Employee.class); List results = cr.list();

//add Restrictions,Criteria cr = session.createCriteria(Employee.class); cr.add(Restrictions.eq("salary", 2000)); List results = cr.list();

Page 27: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Criteria with Restrictions, more examplesCriteria cr = session.createCriteria(Employee.class); // To get records having salary more than 2000 cr.add(Restrictions.gt("salary", 2000)); // To get records having salary less than 2000 cr.add(Restrictions.lt("salary", 2000)); // To get records having fistName starting with zara cr.add(Restrictions.like("firstName", "zara%")); // Case sensitive form of the above restriction. cr.add(Restrictions.ilike("firstName", "zara%")); // To get records having salary in between 1000 and 2000 cr.add(Restrictions.between("salary", 1000, 2000)); // To check if the given property is null cr.add(Restrictions.isNull("salary")); // To check if the given property is not null cr.add(Restrictions.isNotNull("salary")); // To check if the given property is empty cr.add(Restrictions.isEmpty("salary")); // To check if the given property is not empty cr.add(Restrictions.isNotEmpty("salary"));

Page 28: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Sorting results with CriteriaCriteria cr = session.createCriteria(Employee.class); // To get records having salary more than 2000 cr.add(Restrictions.gt("salary", 2000)); // To sort records in descening order crit.addOrder(Order.desc("salary")); // To sort records in ascending order crit.addOrder(Order.asc("salary")); List results = cr.list();

Criteria with and, or

Criteria cr = session.createCriteria(Employee.class); Criterion salary = Restrictions.gt("salary", 2000); Criterion name = Restrictions.ilike("firstNname","zara%"); // To get records matching with OR condistions LogicalExpression orExp = Restrictions.or(salary, name); cr.add( orExp ); // To get records matching with AND condistions LogicalExpression andExp = Restrictions.and(salary, name); cr.add( andExp ); List results = cr.list();

Page 29: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Projections is to retrieve individual properties, rather than entities. For instance, we can retrieve just the name and description from our product table, instead of loading the entire object representation into memory.Criteria crit = session.createCriteria(Product.class);ProjectionList projList = Projections.projectionList();projList.add(Projections.property("name"));projList.add(Projections.property("description"));crit.setProjection(projList);crit.addOrder(Order.asc("price"));List<object[]> results = crit.list();

Page 30: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Why Criteria API?Generally Criteria Queries are used for dynamic queries. For example it is much easier to add some ordering dynamically or leave some parts (e.g. restrictions) out depending on some parameter.On the other hand HQL can be used for static and complex queries, because it's much easier to understand/read HQL. Also, HQL is a bit more powerful, I think, e.g. for different join types.

HQL is to perform both select and non-select operations on the data, but Criteria is only for selecting the data, we cannot perform non-select operations using criteriaHQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic QueriesHQL doesn’t support pagination concept, but we can achieve pagination with CriteriaWith Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection.

Page 31: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Native SQL Queries with HibernateIt is possible to execute Native SQL Queries with Hibernate.

Application will create a native SQL query from the session with the createSQLQuery() method on the Session interface. [purpose of createQuery() ?]

public SQLQuery createSQLQuery(String sqlString) throws HibernateException

Scalar Queries:Below query returns scalar values, basically returning the "raw" values from the resultset. Below is example to get a list of scalars (values) from one or more tables. Following is the syntax for using native SQL for scalar values:

String sql = "SELECT first_name, salary FROM EMPLOYEE"; SQLQuery query = session.createSQLQuery(sql); query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); List results = query.list();

Page 32: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Entity queries Below is the syntax to get entity objects as a whole from a native sql query using addEntity() method.

String sql = "SELECT * FROM EMPLOYEE"; SQLQuery query = session.createSQLQuery(sql); query.addEntity(Employee.class); List results = query.list();

Named SQL Queries Below is example of Named SQL query using addEntity() method.

String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id"; SQLQuery query = session.createSQLQuery(sql); query.addEntity(Employee.class); query.setParameter("employee_id", 21); List results = query.list();

Page 33: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

To Automatically create Tables use below line in hibernate.cfg.xml file<property name="hbm2ddl.auto">update</property>

Page 34: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Hibernate Cachingcache is a local buffer. It improves the performance of application by reducing the number of hit(from Java application) to database. Caching In hibernate are of 2 types :First Level CacheSecond Level Cache

First Level Cache

In Hibernate, when a session is opened then hibernate automatically opens a cache along with that session. When a session is closed then automatically cache also closed. Every session is associated with a corresponding cache. we no need of doing any settings (configurations) either to enable or disable the first level cache.When a program want an object from data base then hibernate first checks for that object in level1 cache. If that object is not existed in level1 cache then it checks in second level cache. If not existed in second level cache, then only hibernate goes to database.

Page 35: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.
Page 36: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

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.Different vendors have provided the implementation of Second Level Cache.1. EH Cache2. Swarm Cache3. OS Cache4. JBoss CacheEach 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.

Page 37: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

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

Page 38: Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from common data persistence.

Hibernate Annotations•Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa. •Hibernate annotations is the newest way to define mappings without a use of XML file. •You can use annotations in addition to or as a replacement of XML mapping metadata. •Hibernate Annotations is other way to provide the metadata for the Object and Relational Table mapping.•All the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development.