Presentation is loading. Please wait.

Presentation is loading. Please wait.

Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from common data persistence.

Similar presentations


Presentation on theme: "Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from common data persistence."— Presentation transcript:

1 Hibernate 4.3

2 Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves 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..

3 Java Application JDBC Driver Database Server Hibernate Framework

4 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.Takes care of Complex associations of objects in your database. 7.Minimize database access with smart fetching strategies. 8.Provides Simple querying of data.

5 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.Hibernate Advantages 1Lets business code access objects rather than DB tables. 2Hides details of SQL queries from OO logic. 3Based on JDBC 'under the hood' 4No need to deal with the database implementation. 5Entities based on business concepts rather than database structure. 6Transaction management and automatic key generation. 7Fast development of application. 8Cache Management 9Automatic creation of required tables in database

6 Hibernate creates a table for every class, and a record/row in the table represents one object.

7 Hibernate Mappings: Below are different mappings which can exist between objects that can be persisted. It is based on composition relation between objects. 1.One to One Mapping 2.One to Many 3.Many to One 4.Many to many

8 To use Hibernate with your Java Application, you need below files 1.Below XML files need to be provided a.hibernate.cfg.xml has Database details b.abc.hbm.xml Hbm means hibernate mapping. This file provides mapping b/n Class and db table, and b/n fields and db columns 2.Persistent Class(es) or POJO(Plain Old Java Objects) 3.Hibernate Jar files 4.JDBC jar file, based on underlying database 5.Java Application, which invokes Hibernate methods

9 Hibernate RelationshipXML Element in hbm fileMapping details stored in db column/ table One to onemany-to-one with unique=“true” Mapping Column is created in Source table Many to Onemany-to-oneColumn in Source table One to Many(source class has Set of Destination objects) one-to-manyColumn in Destination table Many to Many(source class has Set of Destination objects) many-to-manySeparate db table with two columns. One column with id in source table, second column with id in destination table

10 One to one.... <many-to-one name="address" column="emp_address" unique="true" class="Address" not-null="true"/>....

11 Many to one public class Employee{ //... private Address address; //... } class Address{ //... }.... <many-to-one name="address" column="emp_address" class="Address" not-null="true"/>....

12 One to Many public class Employee { //... private Set certificates; //... } class Certificate{ //... }........

13 when ever we apply relationship between objects, cascade attribute transfers operations done on one object onto its related child objects If we write cascade = “all” then changes at parent class object will be effected to child class object too, if we write cascade = “all” then all operations like insert, delete, update at parent object will be effected to child object also Example: if we apply insert(or update or delete) operation on parent class object, then child class objects will also be stored into the database. default value of cascade =”none” means no operations will be transfers to the child class

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

15 FROM Clause Use 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(); //all properties get selected, above

16 SELECT Clause SELECT 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();

17 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();

18 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();

19 ORDER BY Clause To 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();

20 GROUP BY Clause This 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();

21 UPDATE Clause UPDATE 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);

22 DELETE Clause String 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 Clause String 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); Sample Source code: Query qry = session.createQuery("delete from Students E where E.id=:abcd"); qry.setParameter("abcd",3); int res = qry.executeUpdate();

23 Pagination String hql = "FROM Employee"; Query query = session.createQuery(hql); query.setFirstResult(1); query.setMaxResults(10); List results = query.list(); Below are other values for hbm2ddl.auto 1. 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.

24 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

25 Persistent State Hibernate is aware of, and managing, the object Has a database id Already existing object retrieved from the database Formerly transient object about to be saved This is the only state where objects are saved to the database Modifications made in other states are NOT saved to the database while the object remains in that state Changes 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 exists Account account = new Account(); // transition to the ‘persistent’ state. Hibernate is NOW // aware of the object and will save it to the database session.saveOrUpdate(account); // modification of the object will automatically be // saved because the object is in the ‘persistent’ state account.setBalance(500); // commit the transaction session.getTransaction().commit();

26 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 Session session = SessionFactory.getCurrentSession(); // retrieve account with id 1. account is returned in a ‘persistent’ state Account account = session.get(Account.class, 1); // transition to the ‘removed’ state. Hibernate deletes the // database record, and no longer manages the object session.delete(account); // modification is ignored by Hibernate since it is in the ‘removed’ state account.setBalance(500); // commit the transaction session.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 scope account.setBalance(1000);

27 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 Can 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’ state Account account = session1.get(Account.class, 1); // transition to the ‘detached’ state. Hibernate no longer manages the object session1.close(); // modification is ignored by Hibernate since it is in the ‘detached’ // state, but the account still represents a row in the database account.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 database Session session2 = SessionFactory.getCurrentSession(); session2.update(account); // commit the transaction session2.getTransaction().commit();

28 HQL Aggregate Methods 1.avg(property name)The average of a property's value 2.count(property name or *)The number of times a property occurs in the results 3.max(property name)The maximum value of the property values 4.min(property name)The minimum value of the property values 5.sum(property name)The sum total of the property values Query q=session.createQuery("select max(salary) from Emp");

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

30 Requirements of a POJO class 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.

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

32 Hibernate Mapping Types When 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.

33 Hibernate Mapping typeJava typeSQL Type integerint or java.lang.IntegerINTEGER longlong or java.lang.LongBIGINT shortshort or java.lang.ShortSMALLINT floatfloat or java.lang.FloatFLOAT doubledouble or java.lang.DoubleDOUBLE big_decimaljava.math.BigDecimalNUMERIC characterjava.lang.StringCHAR(1) stringjava.lang.StringVARCHAR bytebyte or java.lang.ByteTINYINT booleanboolean or java.lang.BooleanBIT yes/noboolean or java.lang.BooleanCHAR(1) ('Y' or 'N') true/falseboolean or java.lang.BooleanCHAR(1) ('T' or 'F')

34 Mapping type Java typeANSI SQL Type datejava.util.Date or java.sql.DateDATE timejava.util.Date or java.sql.TimeTIME timestampjava.util.Date or java.sql.Timestamp TIMESTAMP calendarjava.util.CalendarTIMESTAMP calendar_dat e java.util.CalendarDATE

35 Hibernate Criteria API Hibernate 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 class Criteria 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();

36 Criteria with Restrictions, more examples Criteria 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"));

37 Sorting results with Criteria Criteria 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();

38 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 results = crit.list();

39 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 criteria HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries HQL doesn’t support pagination concept, but we can achieve pagination with Criteria With 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.

40 Native SQL Queries with Hibernate It 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();

41 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();

42 To Automatically create Tables use below line in hibernate.cfg.xml file update

43 Hibernate Caching cache 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 Cache Second 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.

44

45 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 Cache 2.Swarm Cache 3.OS Cache 4.JBoss Cache 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.

46 The cache-usage property can be applied in hbm.xml file. The example to define cache usage is given below: CacheEventListenerAdapter notifyElementUpdated public void notifyElementUpdated(Ehcache cache, Element element) throws CacheExceptionCalled immediately after an element has been put into the cache and the element already existed in the cache. This is thus an update.Ehcache ElementCacheException public void notifyElementPut(Ehcache cache, Element element)Ehcache Element public void notifyElementRemoved(Ehcache cache, Element element) throws CacheExceptionEhcache ElementCacheException

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


Download ppt "Hibernate 4.3. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from common data persistence."

Similar presentations


Ads by Google