690 likes | 824 Views
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 ?.
E N D
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?
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
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”) );
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 );
Employee – Application Object public class Employee { Integer id; String name; Employee supervisor; }
Employee – Database Table create table employees ( id integer primary key, name varchar(255), supervisor integer references employees(id) );
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 … … } }
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 = ?” ); … }
… 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”); … } }
… 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 = ?? } }
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
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.
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);
The ORM Approach employee Application customer account ORM tool Oracle, MySQL, SQL Server … Flat files, XML … Persistent Data Store
Hibernate Architecture Hibernate sits between your code and the database Maps persistent objects to tables in the database
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
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) {} ……}
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) );
Hibernate Configuration File • Important properties to configure your database
Mapping Class to Table Employee.hbm.xml
Hibernate mapping types • Hibernate will translate Java types to SQL / database types for the properties of your mapped classes
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
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();
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();
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();
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
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();
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();
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();
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();
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();
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%"));
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();
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();
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();
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(); } } }
Mappings (CH.11) • Collection mapping • Association mapping • Component mapping
Collection Mapping • Hibernate can persist instances of the given collection types