1 / 69

Object-Relational Mapping with Hibernate

Object-Relational Mapping with Hibernate. The Object-Oriented Paradigm. The world consists of objects So we use object-oriented languages to write applications We want to store some of the application objects (a.k.a. persistent objects ) So we use a Object Database ?.

Télécharger la présentation

Object-Relational Mapping with Hibernate

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object-Relational Mapping with Hibernate

  2. The Object-Oriented Paradigm • The world consists of objects • So we use object-oriented languages to write applications • We want to store some of the application objects (a.k.a. persistent objects) • So we use a Object Database?

  3. The Reality of DBMS • Relational DBMS are still predominant • Best performance • Most reliable • Widest support • Bridge between OO applications and relational databases • CLI and embedded SQL (JDBC) • Object-Relational Mapping (ORM) tools

  4. JDBC Call-Level Interface (CLI) • Application interacts with database through functions calls String sql = "select name from items where id = 1"; Connection c = DriverManager.getConnection( url ); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( sql ); if( rs.next() ) System.out.println( rs.getString(“name”) );

  5. Embedded SQL • SQL statements are embedded in host language String name; #sql {select name into :name from items where id = 1}; System.out.println( name );

  6. Employee – Application Object public class Employee { Integer id; String name; Employee supervisor; }

  7. Employee – Database Table create table employees ( id integer primary key, name varchar(255), supervisor integer references employees(id) );

  8. From Database to Application • So how do we construct an Employee object based on the data from the database? public class Employee { Integer id; String name; Employee supervisor; public Employee( Integer id ) { // access database to get name and supervisor … … } }

  9. Problems with CLI and Embedded SQL … • SQL statements are hard-coded in applications public Employee( Integer id ) { … PreparedStatment p; p = connection.prepareStatment( “select * from employees where id = ?” ); … }

  10. … Problems with CLI and Embedded SQL … • Tedious translation between application objects and database tables public Employee( Integer id ) { … ResultSet rs = p.executeQuery(); if( rs.next() ) { name = rs.getString(“name”); … } }

  11. … Problems with CLI and Embedded SQL • Application design has to work around the limitations of relational DBMS public Employee( Integer id ) { … ResultSet rs = p.executeQuery(); if( rs.next() ) { … supervisor = ?? } }

  12. What is Hibernate? • It is an object-relational mapping (ORM) solution that allows for persisting Java objects in a relational database • Open source • Development started late 2001

  13. Object-Relational Mapping • It is a programming technique for converting object-type data of an object oriented programming language into database tables. • Hibernate is used convert object data in JAVA to relational database tables.

  14. Hibernate vs. JDBC (an example) • JDBC tuple insertion – st.executeUpdate(“INSERT INTO book VALUES(“Harry Potter”,”J.K.Rowling”)); • Hibernate tuple insertion – session.save(book1);

  15. The ORM Approach employee Application customer account ORM tool Oracle, MySQL, SQL Server … Flat files, XML … Persistent Data Store

  16. Hibernate Architecture Hibernate sits between your code and the database Maps persistent objects to tables in the database

  17. Hibernate Example

  18. Java Classes • Plain Java classes (POJOs); however, it is recommended that • Each persistent class has an identity field • Each persistent class has no argument constructor • Each persistent field has a pair of getter and setter, which don’t have to be public

  19. Employee Persistable Class public class Employee { private int id; ; Identifier property private String first_name; private String last_name; private int salary; public Employee() {} ;No-argument constructor ; Getters and Setters public intgetId() {} public void setId(int ID) {} ……}

  20. Database Table • Persistable classes have an associated table create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );

  21. Hibernate Configuration File • Important properties to configure your database

  22. Hibernate Configuration file - hibernate.cfg.xml

  23. Mapping Class to Table Employee.hbm.xml

  24. Hibernate mapping types • Hibernate will translate Java types to SQL / database types for the properties of your mapped classes

  25. Hibernate Detailed Arch.

  26. Configuration • Represents a set of mapping files • Database Connection: Handled through one or more configuration files. These files are hibernate.propertiesand hibernate.cfg.xml. • Class Mapping Setup: Creates the connection between the Java classes and database tables

  27. Session Factory • Obtained from a Configuration instance • Shared among application threads • Main purpose is to provide Session instances • Created during application start up and kept for later use. • You would need one SessionFactoryobject per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactoryobjects. private static SessionFactoryfactory= new Configuration().configure().buildSessionFactory();

  28. Session • Lightweight and inexpensive to create/destroy • Not threadsafe – each thread needs its own • Obtained from SessionFactory instance Session session = sessionFactory.openSession(); // perform persistence operations session.close();

  29. Transaction • Set of operations that are all committed or all rolled back • Obtained from Session instance • Can perform multiple transactions within session Transaction tx = session.beginTransaction(); // perform persistence operations tx.commit();

  30. Object Lifecycle • Transient • Newly created object • Persistent • New object has been “saved” • Previously saved object has been “read” • Detached • Session closed • Can be reattached later to become persistent

  31. Query Options (CH.13,14,15) • Hibernate Query Language (HQL) Query q = session.createQuery(“from Employee Ewhere e.salary> :value”); q.setParameter(“value”, someValue); List widgets = q.list(); • Criteria API Criteria cr = session.createCriteria(Employee.class); cr.add(Restrictions.eq("salary", 2000)); List results = cr.list(); • Native SQL Query q = session.createSQLQuery(“"SELECT * FROM EMPLOYEE ”); List Employees = q.list();

  32. 1- Hibernate Query Language • FROM Clause String hql = "FROM Employee"; Query query = session.createQuery(hql); List results = query.list(); - AS Clause String hql = "FROM Employee AS E"; Query query = session.createQuery(hql); List results = query.list();

  33. Hibernate Query Language(1) • Where Clause String hql = "FROM Employee E WHERE E.id = 10"; Query query = session.createQuery(hql); List results = query.list(); • ORDER BY Clause String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC"; Query query = session.createQuery(hql); List results = query.list();

  34. Hibernate Query Language(2) • 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(); • 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();

  35. Hibernate Query Language(3) • Paging Using Query String hql = "FROM Employee"; Query query = session.createQuery(hql); query.setFirstResult(0); query.setMaxResults(10); List results = query.list();

  36. 2- Restrictions with Criteria Criteria cr = session.createCriteria(Employee.class); cr.add(Restrictions.eq("salary", 2000)); // 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%"));

  37. Sorting Using Criteria Package org.hibernate.criterion.Order : 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();

  38. 3- Hibernate Native SQL Scalar queries : String sql = "SELECT first_name, salary FROM EMPLOYEE"; SQLQuery query = session.createSQLQuery(sql); List results = query.list(); Entity queries : String sql = "SELECT * FROM EMPLOYEE"; SQLQuery query = session.createSQLQuery(sql); query.addEntity(Employee.class); List results = query.list();

  39. 3- Hibernate Native SQL(1) Named SQL queries : String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id"; SQLQuery query = session.createSQLQuery(sql); query.addEntity(Employee.class); query.setParameter("employee_id", 10); List results = query.list();

  40. Example Application

  41. Example Application

  42. Example Application

  43. Example Application

  44. Example Application /* Method to DELETE an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); session.delete(employee); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } }

  45. Mappings (CH.11) • Collection mapping • Association mapping • Component mapping

  46. Collection Mapping • Hibernate can persist instances of the given collection types

  47. Collection Mapping Set ex.

  48. Collection Mapping Set ex.

  49. Collection Mapping Set ex.

  50. Collection Mapping Set ex.

More Related