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.

Slides:



Advertisements
Similar presentations
Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
Advertisements

.NET Database Technologies: Open-Source Frameworks.
Hibernate 1. Introduction ORM goal: Take advantage of the things SQL databases do well, without leaving the Java language of objects and classes. ORM.
Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
Session-02.
RIZWAN REHMAN, CCS, DU. Advantages of ORDBMSs  The main advantages of extending the relational data model come from reuse and sharing.  Reuse comes.
Session-01. Hibernate Framework ? Why we use Hibernate ?
An Introduction to Hibernate Matt Secoske
Data Persistence and Object-Relational Mapping Slides by James Brucker, used with his permission 1.
Hibernatification! Roadmap for Migrating from Plain Old SQL on JDBC to JPA on Hibernate Duke Banerjee Senior Developer, DrillingInfo.com.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
LINQ Boot Camp ADO.Net Entity Framework Presenter : Date : Mahesh Moily Nov 26, 2009.
Database Programming in Java Corresponds with Chapter 32, 33.
1 J2EE Components. 2 Application Servers relieve the programming burden for business distributed components. They provide support for system level services.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
Object persistence with Hibernate in Decision Deck 1.1 Gilles Dodinet 2 nd Decision Deck Workshop 2008, February.
Database Technical Session By: Prof. Adarsh Patel.
Data File Access API : Under the Hood Simon Horwith CTO Etrilogy Ltd.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
PowerPoint Presentation for Dennis, Wixom, & Tegarden Systems Analysis and Design with UML, 4th Edition Copyright © 2009 John Wiley & Sons, Inc. All rights.
Object Oriented Analysis and Design 1 Chapter 7 Database Design  UML Specification for Data Modeling  The Relational Data Model and Object Model  Persistence.
Lecture2: Database Environment Prepared by L. Nouf Almujally & Aisha AlArfaj 1 Ref. Chapter2 College of Computer and Information Sciences - Information.
Database, SQL, and ADO.NET- Part 1 Session 11 Mata kuliah: M0874 – Programming II Tahun: 2010.
JDBC Java and Databases. RHS – SOC 2 JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
Object-to-Relational Mapping: The Crossing Chasms Pattern and Implementation Considerations Use of Meta Data in the Java Persistence Layer Presented by.
Database Programming Sections 11 & 12 – Creating, and Managing Views, Sequences, Indexes, and Synonymns.
Hibernate Persistence. What is Persistence Persist data to database or other storage.  In OO world, persistence means persist object to external storage.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Efficient RDF Storage and Retrieval in Jena2 Written by: Kevin Wilkinson, Craig Sayers, Harumi Kuno, Dave Reynolds Presented by: Umer Fareed 파리드.
Nikolay Kostov Telerik Corporation
A U.S. Department of Energy Office of Science Laboratory Operated by The University of Chicago Argonne National Laboratory Office of Science U.S. Department.
JPA / HIBERNATE CSCI 6370 Nilayan Bhattacharya Sanket Sable.
XML and Database.
Hibernate Thuy, Le Huu Pentalog HAN. What is Hibernate? Hibernate is a free, open source Java package that makes it easy to work with relational databases.
Class Builder Tutorial Presented By- Amit Singh & Sylendra Prasad.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Session 1 Module 1: Introduction to Data Integrity
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Persistence – Iteration 4 Vancouver Bootcamp Aaron Zeckoski
PowerPoint Presentation for Dennis, Wixom, & Tegarden Systems Analysis and Design with UML, 5th Edition Copyright © 2015 John Wiley & Sons, Inc. All rights.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Introduction – ORM, Helloworld Application
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
Unit-8 Introduction Of MySql. Types of table in PHP MySQL supports various of table types or storage engines to allow you to optimize your database. The.
Introduction to ORM Hibernate Hibernate vs JDBC. May 12, 2011 INTRODUCTION TO ORM ORM is a programming technique for converting data between relational.
CS422 Principles of Database Systems Object-Relational Mapping (ORM) Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Hibernate Online Training. Introduction to Hibernate Hibernate is a high-performance Object-Relational persistence and query service which takes care.
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.
Hibernate Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
Views / Session 3/ 1 of 40 Session 3 Module 5: Implementing Views Module 6: Managing Views.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
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.
Fundamentals of DBMS Notes-1.
JDBC.
Entity Framework By: Casey Griffin.
Java Data Persistence Using Hibernate
Chapter 8 Advanced SQL.
Developing and testing enterprise Java applications
Presentation transcript:

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

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.

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

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.

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

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

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

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

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

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

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

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

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.

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

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

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

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

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");

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

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.

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.

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.

Mapping typeJava typeANSI SQL 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')

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

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

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"));

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

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

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.

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

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

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

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.

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.

The cache-usage property can be applied in hbm.xml file. The example to define cache usage is given below:

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.