hibernate thuy, le huu pentalog han. what is hibernate? hibernate is a free, open source java...

49
Hibernate Thuy, Le Huu Pentalog HAN

Upload: april-poole

Post on 13-Dec-2015

224 views

Category:

Documents


1 download

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

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

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

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping> <class name="com.pentalog.ginet.domain.Employee" table="employee"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class></hibernate-mapping>

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<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="connection.url">jdbc:hsqldb:file:D:\\Hibernate-tut\\hsqldb-2.2.9\\ginet</property> <property name="connection.username">SA</property> <property name="connection.password">SA</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.HSQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <!-- Mapping files --> <mapping resource="com/pentalog/ginet/Star.hbm.xml"/> </session-factory></hibernate-configuration>

Multiple Databasespublic 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.xmlreturn 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 ClauseString hql = "FROM Employee";

AS ClauseString hql = "FROM Employee AS E";

SELECT ClauseString hql = "SELECT E.firstName FROM Employee E";

WHERE ClauseString hql = "FROM Employee E WHERE E.id = 10";

ORDER BY ClauseString hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary

DESC";

Hibernate Query Language

GROUP BY ClauseString hql = "SELECT SUM(E.salary), E.firtName FROM Employee E GROUP

BY E.firstName";

Using Named ParamtersString 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 ClauseString hql = "UPDATE Employee set salary = :salary " + "WHERE id

= :employee_id";

DELETE ClauseString hql = "DELETE FROM Employee " + "WHERE id = :employee_id";

Hibernate Query Language

Aggregate MethodsS.N. Functions Description

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

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 CriteriaCriteria 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 queryCriteria cr = session.createCriteria(Employee.class);

List results = cr.list();

Restrictions with CriteriaCriteria 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<query name="find.users.access.greaterthan.50">

<! [CDATA[from users user where user > 50]]>

</query>

Query query = session.getNamedQuery("find.users.access.greaterthan.50"); List users = query.list();

Named Queries

With parameters<query name="find.users.access.greaterthan">

<! [CDATA[from users user where user.id> ?]]>

</query>

Query query = session.getNamedQuery("find.users.access.greaterthan"); query.setInt(0, 100);List users = query.list();

Named Parameter

With parameters<query name="find.users.access.greaterthan">

<! [CDATA[from users user where user > :abc]]>

</query>

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 type Mapping and Description

java.util.Set This is mapped with a <set> element and initialized with java.util.HashSet

java.util.SortedSetThis is mapped with a <set> 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 <list> element and initialized with java.util.ArrayList

java.util.Collection This is mapped with a <bag> or <ibag> element and initialized with java.util.ArrayList

java.util.Map This is mapped with a <map> element and initialized with java.util.HashMap

java.util.SortedMapThis is mapped with a <map> element and initialized with java.util.TreeMap. The sort attribute can be set to either a comparator or natural ordering.

Hibernate List Mappings<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping> <class name="com.pentalog.ginet.domain.PEmployee" table="employee"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <list name="certificates" cascade="all"> <key column="employee_id"/> <list-index column="idx"/> <one-to-many class="com.pentalog.ginet.domain.Certificate"/> </list> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> <class name="com.pentalog.ginet.domain.Certificate" table="certificate"> <meta attribute="class-description"> This class contains the certificate records. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class></hibernate-mapping>

Association Mappings

Mapping type Description

Many-to-One Mapping many-to-one relationship using Hibernate

One-to-One Mapping one-to-one relationship using Hibernate

One-to-Many Mapping one-to-many relationship using Hibernate

Many-to-Many Mapping many-to-many relationship using Hibernate

Many-to-One

<hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> <many-to-one name="address" column="address" class="Address" not-null="true"/> </class>

<class name="Address" table="ADDRESS"> <meta attribute="class-description"> This class contains the address detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="street" column="street_name" type="string"/> <property name="city" column="city_name" type="string"/> <property name="state" column="state_name" type="string"/> <property name="zipcode" column="zipcode" type="string"/> </class>

</hibernate-mapping>

One-to-One

<hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> <many-to-one name="address" column="address" unique="true" class="Address" not-null="true"/> </class>

<class name="Address" table="ADDRESS"> <meta attribute="class-description"> This class contains the address detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="street" column="street_name" type="string"/> <property name="city" column="city_name" type="string"/> <property name="state" column="state_name" type="string"/> <property name="zipcode" column="zipcode" type="string"/> </class>

One-to-Many<hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <set name="certificates" cascade="all"> <key column="employee_id"/> <one-to-many class="Certificate"/> </set> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class>

<class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class>

</hibernate-mapping>

Many-to-Many

<hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <set name="certificates" cascade="save-update" table="EMP_CERT"> <key column="employee_id"/> <many-to-many column="certificate_id" class="Certificate"/> </set> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class>

<class name="Certificate" table="CERTIFICATE"> <meta attribute="class-description"> This class contains the certificate records. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="name" column="certificate_name" type="string"/> </class>

</hibernate-mapping>

Many-to-Many example

Many-to-Many example

<hibernate-mapping> <class name="com.pentalog.ginet.domain.Student" table="student"> <meta attribute="class-description"> This class contains the student detail. </meta> <id name="id" type="int" column="STUDENT_ID"> <generator class="native"/> </id> <set name="courses" cascade="save-update" table="student_course"> <key column="STUDENT_ID"/> <many-to-many column="COURSE_ID" class="com.pentalog.ginet.domain.Course"/> </set> <property name="studentName" column="STUDENT_NAME" type="string"/> </class> <class name="com.pentalog.ginet.domain.Course" table="course"> <meta attribute="class-description"> This class contains the course records. </meta> <id name="id" type="int" column="COURSE_ID"> <generator class="native"/> </id> <property name="courseName" column="COURSE_NAME" type="string"/> </class></hibernate-mapping>

Many-to-Many example

try{ tx = session.beginTransaction(); List<Student> students = session.createQuery("FROM Student").list(); for (Iterator<Student> iterator1 = students.iterator(); iterator1.hasNext();){ Student student = (Student) iterator1.next(); System.out.println("\tFirst Name:\t" + student.getStudentName()); Set<Course> certificates = student.getCourses(); for (Iterator<Course> 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 type Description

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

Component Mappings

<hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <component name="address" class="Address"> <property name="street" column="street_name" type="string"/> <property name="city" column="city_name" type="string"/> <property name="state" column="state_name" type="string"/> <property name="zipcode" column="zipcode" type="string"/> </component> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class></hibernate-mapping>

Next class

hibernate AnnotationsImproving performance

Lazy loadingCachingBatch processing

LockingVersioning

Thank you!!!