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.

Slides:



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

Distributed Application Development B. Ramamurthy.
Hibernate 1. Introduction ORM goal: Take advantage of the things SQL databases do well, without leaving the Java language of objects and classes. ORM.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
ODBC and JDBC O/R Mapping Amit Shabtay. June 2nd, 2004 Object Oriented Design Course 2 Objects And Databases Most of the applications today are written.
Session-02.
Session-01. Hibernate Framework ? Why we use Hibernate ?
An Introduction to Hibernate Matt Secoske
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
The Easiest Way To Learn Hibernate: YouTube Videos and the Online Tutorial
Object Persistence using Hibernate
Fresher Technology Specific - JAVA Stream Hibernate Framework
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
JDBC and Hibernate Joshua Scotton. Connecting to Relational DBs.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
CS 157B: Database Management Systems II January 30 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
Robert Greiner CSE7330 Southern Methodist University Getting Things Done with Hibernate.
Seminar on. Overview Hibernate. What is it? Hibernate. How does it work? Hibernate Tools.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Object/Relational Mapping with Hibernate Practical ORM.
CS 157B: Database Management Systems II February 6 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CS 160: Software Engineering November 5 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
CS 157B: Database Management Systems II January 28 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
CS 160: Software Engineering October 1 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
© 2011 Pearson Education, Inc. Publishing as Prentice Hall 1 Chapter 14 Using Relational Databases to Provide Object Persistence (Overview) Modern Database.
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.
Hibernate Introduction - 1 Present by Eric Yu. BeanSoft | 2 Content Understanding object/relational persistence Introduction Architecture The core interfaces.
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.
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.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
Persistence – Iteration 4 Vancouver Bootcamp Aaron Zeckoski
Basics of JDBC Session 14.
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February
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.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
Hibernates - Many to One Association. May 12, 2011 What is Association? Association is the relation between two objects. One class holds a reference of.
MANY-TO-MANY MAPPING. May 12, 2011  Implemented using a Set java collection  Mediator table is mandatory – Join table  Join table contains foreign.
Introduction to ORM Hibernate Hibernate vs JDBC. May 12, 2011 INTRODUCTION TO ORM ORM is a programming technique for converting data between relational.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
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 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.
JDBC.
Современные технологии баз данных Лекция 7. Объектно-реляционное отображение (ORM) Технология отображения объектов какого- либо объектно-ориентированного.
Introduction to Database Programming with Python Gary Stewart
HIBERNATE/Java Overview of technology for Hibernate by محمد حسن کاظمی پوران Master : M.M.Nematollahi.
Chengyu Sun California State University, Los Angeles
A very brief introduction
JDBC.
Java Data Persistence Using Hibernate
Interacting with Database
Hibernate Bayu Priyambadha, S.Kom.
Java Database Connectivity
Chengyu Sun California State University, Los Angeles
Presentation transcript:

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. Hibernate is an Object-Relational Mapping(ORM) solution for Java Hibernate makes it seem as if your database contains plain Java objects like you use every day, without having to worry about how to get them out of (or back into) mysterious database tables. Hibernate liberates you to focus on the objects and features of your application, without having to worry about how to store them or find them later.

ORM 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, C# etc

Hibernate Advantages ? Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code. Provides simple APIs for storing and retrieving Java objects directly to and from the database. If there is change in Database or in any table then the only need to change XML file properties.

Hibernate Advantages ? Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects. Hibernate does not require an application server to operate. Manipulates Complex associations of objects of your database. Minimize database access with smart fetching strategies. Provides Simple querying of data

Hibernate Support Different Database DB2 MySQL PostgreSQL Oracle (any version) Microsoft SQL Server HypersonicSQL Informix Ingres Interbase Pointbase Mckoi SQL Progress FrontBase SAP DB Sybase

Hibernate Architecture high level view of the Hibernate Application Architecture

Hibernate Architecture Detailed view of the Hibernate Application Architecture with few important core classes.

Hibernate Architecture Hibernate architecture has three main components: Connection Management Hibernate Connection management service provide efficient management of the database connections. Database connection is the most expensive part of interacting with the database as it requires a lot of resources of open and close the database connection. Transaction management: Transaction management service provide the ability to the user to execute more than one database statements at a time. Object relational mapping: Object relational mapping is technique of mapping the data representation from an object model to a relational data model. This part of the hibernate is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query.

How to Implement Hibernate Hibernate Configuration Persistence Class Map the Object to the Database table Setting up the Database

Hibernate Configuration.N.Properties and Description 1 hibernate.dialect This property makes Hibernate generate the appropriate SQL for the chosen database. 2 hibernate.connection.driver_class The JDBC driver class. 3 hibernate.connection.url The JDBC URL to the database instance. 4 hibernate.connection.username The database username. 5 hibernate.connection.password The database password. 6 hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.

Hibernate Configuration

2. Persistence Class public class Employee implements Serializable { private static final long serialVersionUID = 1L; private int id; private String firstName; private String lastName; private int salary; public Employee() { } public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String first_name) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName(String last_name) { this.lastName = last_name; }

3.Map the Object to the Database table <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" " This class contains the employee detail.

4.Setting up the Database public class TestManageEmployee { private static SessionFactory factory; public static void main(String[] args) { try { factory = new Configuration().configure().buildSessionFactory(); }catch (Throwable ex) {throw new ExceptionInInitializerError(ex);} TestManageEmployee ME = new TestManageEmployee(); ME.listEmployees(); public void listEmployees() { Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); List employees = session.createQuery("FROM Employee").list(); for (Iterator iterator = employees.iterator(); iterator.hasNext();) { Employee employee = (Employee) iterator.next(); System.out.print("First Name: " + employee.getFirstName()); System.out.print("Last Name: " + employee.getLastName()); System.out.println("Salary: " + employee.getSalary()); } tx.commit(); } catch (HibernateException e) { if (tx != null) tx.rollback(); e.printStackTrace(); } finally {session.close();} }

Multiple Databases hsql

Multiple Databases <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" " org.hsqldb.jdbcDriver jdbc:hsqldb:file:D:\\Hibernate-tut\\hsqldb-2.2.9\\ginet SA 1 org.hibernate.dialect.HSQLDialect thread org.hibernate.cache.NoCacheProvider true update

Multiple Databases public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static final SessionFactory sessionFactoryHSQL = buildSessionFactoryHSQL(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } private static SessionFactory buildSessionFactoryHSQL() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure("hsql.cfg.xml").buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory HSQL creation failed." + ex); throw new ExceptionInInitializerError(ex); } public static SessionFactory getSessionFactory() { return sessionFactory; } public static SessionFactory getSessionFactoryHSQL() { return sessionFactoryHSQL; }

Query in Hibernate Hibernate provides three full-featured query facilities:  Hibernate Query Language  Hibernate Criteria Query API  Hibernate Native Query

Hibernate Query Language 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

Hibernate Query Language FROM Clause String hql = "FROM Employee"; AS Clause String hql = "FROM Employee AS E"; SELECT Clause String hql = "SELECT E.firstName FROM Employee E"; WHERE Clause String hql = "FROM Employee E WHERE E.id = 10"; ORDER BY Clause String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";

Hibernate Query Language GROUP BY Clause String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E GROUP BY E.firstName"; Using Named Paramters String hql = "FROM Employee E WHERE E.id = :employee_id"; Query query = session.createQuery(hql); query.setParameter("employee_id",10); List results = query.list();

Hibernate Query Language UPDATE Clause String hql = "UPDATE Employee set salary = :salary " + "WHERE id = :employee_id"; DELETE Clause String hql = "DELETE FROM Employee " + "WHERE id = :employee_id";

Hibernate Query Language Aggregate Methods S.N.FunctionsDescription 1avg(property name)The average of a property's value 2count(property name or *)The number of times a property occurs in the results 3max(property name)The maximum value of the property values 4min(property name)The minimum value of the property values 5sum(property name)The sum total of the property values String hql = "SELECT count(distinct E.firstName) FROM Employee E"; Query query = session.createQuery(hql); List results = query.list();

Hibernate Query Language Pagination using Query  setFirstResult(int startPosition)  setMaxResults(int maxResult) String hql = "FROM Employee"; Query query = session.createQuery(hql); query.setFirstResult(1);

Hibernate Criteria Query API Restrictions with Criteria Criteria cr = session.createCriteria(Employee.class); Criterion esalary = Restrictions.gt("salary", 2000); Criterion ename = Restrictions.ilike("firstNname","zara%"); LogicalExpression orExp = Restrictions.or(esalary, ename); cr.add( orExp ); LogicalExpression andExp = Restrictions.and(esalary, ename); cr.add( andExp ); List results = cr.list();

Hibernate Criteria Query API Example of a criteria query Criteria cr = session.createCriteria(Employee.class); List results = cr.list(); Restrictions with Criteria Criteria cr = session.createCriteria(Employee.class); cr.add(Restrictions.eq("salary", 2000)); List results = cr.list(); cr.add(Restrictions.lt("salary", 2000)); cr.add(Restrictions.like("firstName", "zara%")); cr.add(Restrictions.isNull("salary")); cr.add(Restrictions.between("salary", 1000, 2000));

Hibernate Criteria Query API Pagination using Criteria  setFirstResult(int startPosition)  setMaxResults(int maxResult) Criteria cr = session.createCriteria(Employee.class); cr.setFirstResult(1); cr.setMaxResults(10); List results = cr.list();

Hibernate Criteria Query API Sorting the Results Criteria cr = session.createCriteria(Employee.class); cr.add(Restrictions.gt("salary", 2000)); crit.addOrder(Order.desc("salary")); crit.addOrder(Order.asc("salary")); List results = cr.list();

Hibernate Criteria Query API Projections & Aggregations: Criteria cr = session.createCriteria(Employee.class); // To get total row count. cr.setProjection(Projections.rowCount()); // To get average of a property. cr.setProjection(Projections.avg("salary")); // To get minimum of a property. cr.setProjection(Projections.min("salary"));

Hibernate Native Query Session session = factory.openSession(); Transaction tx = null; Integer employeeID = null; try { tx = session.beginTransaction(); TimerGinet time = new TimerGinet("TestManageEmployee"); String sql = "SELECT * FROM EMPLOYEE AS E order by E.first_name"; SQLQuery query = session.createSQLQuery(sql); query.addEntity(Employee.class); List results = query.list(); for (int i = 0; i < results.size(); i++) { System.out.println("First Name: " + ((Employee)results.get(i)).getFirstName()); } tx.commit(); time.done(); } catch (HibernateException e) { if (tx != null) tx.rollback(); e.printStackTrace(); } finally { session.close(); }

Named Queries Without parameters 50]]> Query query = session.getNamedQuery("find.users.access.greaterthan.50"); List users = query.list();

Named Queries With parameters ?]]> Query query = session.getNamedQuery("find.users.access.greaterthan"); query.setInt(0, 100); List users = query.list();

Named Parameter With parameters :abc]]> Query query = session.getNamedQuery("find.users.access.greaterthan"); query.setInt(“abc”, 100); List users = query.list();

Hibernate O/R Mappings Collections Mappings Association Mappings Component Mappings

Collections Mappings Collection typeMapping and Description java.util.Set This is mapped with a element and initialized with java.util.HashSet java.util.SortedSet This is mapped with a element and initialized with java.util.TreeSet. The sort attribute can be set to either a comparator or natural ordering. java.util.List This is mapped with a element and initialized with java.util.ArrayList java.util.Collection This is mapped with a or element and initialized with java.util.ArrayList java.util.Map This is mapped with a element and initialized with java.util.HashMap java.util.SortedMap This is mapped with a element and initialized with java.util.TreeMap. The sort attribute can be set to either a comparator or natural ordering.

Hibernate List Mappings <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" " This class contains the employee detail. This class contains the certificate records.

Association Mappings Mapping typeDescription Many-to-OneMapping many-to-one relationship using Hibernate One-to-OneMapping one-to-one relationship using Hibernate One-to-ManyMapping one-to-many relationship using Hibernate Many-to-ManyMapping many-to-many relationship using Hibernate

Many-to-One This class contains the employee detail. <many-to-one name="address" column="address" class="Address" not-null="true"/> This class contains the address detail.

One-to-One This class contains the employee detail. <many-to-one name="address" column="address" unique="true" class="Address" not-null="true"/> This class contains the address detail.

One-to-Many This class contains the employee detail. This class contains the certificate records.

Many-to-Many This class contains the employee detail. This class contains the certificate records.

Many-to-Many example

This class contains the student detail. This class contains the course records.

Many-to-Many example try{ tx = session.beginTransaction(); List students = session.createQuery("FROM Student").list(); for (Iterator iterator1 = students.iterator(); iterator1.hasNext();){ Student student = (Student) iterator1.next(); System.out.println("\tFirst Name:\t" + student.getStudentName()); Set certificates = student.getCourses(); for (Iterator iterator2 = certificates.iterator(); iterator2.hasNext();){ Course certName = (Course) iterator2.next(); System.out.println("\tCourse:\t" + certName.getCourseName()); } tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); }

Component Mappings Mapping typeDescription Component Mappings Mapping for a class having a reference to another class as a member variable.

Component Mappings This class contains the employee detail.

Next class hibernate Annotations Improving performance  Lazy loading  Caching  Batch processing Locking Versioning

Thank you!!!