Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Hibernate Thuy, Le Huu Pentalog HAN

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

3 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

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

5 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

6 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

7 Hibernate Architecture high level view of the Hibernate Application Architecture

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

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

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

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

12 Hibernate Configuration

13 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; }

14 3.Map the Object to the Database table <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> This class contains the employee detail.

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

16 Multiple Databases hsql

17 Multiple Databases <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 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

18 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; }

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

20 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

35 Hibernate O/R Mappings Collections Mappings Association Mappings Component Mappings

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

37 Hibernate List Mappings <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> This class contains the employee detail. This class contains the certificate records.

38 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

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

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

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

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

43 Many-to-Many example

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

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

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

47 Component Mappings This class contains the employee detail.

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

49 Thank you!!!


Download ppt "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."

Similar presentations


Ads by Google