Hibernate Training Day 1

download Hibernate Training Day 1

of 49

Transcript of Hibernate Training Day 1

  • 8/2/2019 Hibernate Training Day 1

    1/49

    CONFIDENTIAL

    Hibernate Object Relation MapperNovember 24, 2008

  • 8/2/2019 Hibernate Training Day 1

    2/49

    Financial Services| Capital MarketsCONFIDENTIAL

    1

    Purpose

    To learn about hibernate persistence framework and its architecture

    To learn how hibernate is configured and what are the componentsrequired in an application using hibernate

    To learn what are the types of objects and how to work with them

    To understand various associations & how to map them.

    To master HQL and other fetching strategies

    To learn inheritance and component mapping

    To understand how to modify data

    An overview of cache management, transaction management andother advanced features

  • 8/2/2019 Hibernate Training Day 1

    3/49

    Financial Services| Capital MarketsCONFIDENTIAL

    2

    Introduction to different ways of persisting data

    Without Databases

    Object Serialization

    Uses the file system for storing the serialized object forms. Not a object relation mapping technique. Only accessible through java language. Bad choice for storing enterprise data.

    With Databases (RDBMS )

    JDBC

    Simply provide API accessing database, No object relation mapping technique

    Database dependent code Entity Beans (BMP and CMP)

    EJB require a one-to-one mapping to database tables Requires application server supporting EJB Container

    JDO

    Commercial from individual vendors. Mappings not standard

    O/R Mapping tool like Hibernate

    Rich features with total abstraction to databases. Provides resolutions to majority concerns on OR mapping.

  • 8/2/2019 Hibernate Training Day 1

    4/49

    Financial Services| Capital Markets

    Object Serialization Example

    Creating a simple Hashtable and serialize it to a file calledHTExample.ser.

    FileOutputStream fileOut = new FileOutputStream("HTExample.ser");

    ObjectOutputStream out = new ObjectOutputStream(fileOut);out.writeObject(h); //h is an hashMap object with values.

    Reading the Serialized object data stored in the file to theactual object:

    FileInputStream fileIn = new FileInputStream("HTExample.ser");ObjectInputStream in = new ObjectInputStream(fileIn);

    h = (Hashtable)in.readObject();

  • 8/2/2019 Hibernate Training Day 1

    5/49

    Financial Services| Capital Markets

    JDBC Example

    JDBC API used for writing database applications in Javaby making database connections.

    Loading a database driver :

    Class.forName(com.mysql.jdbc.Driver);

    Creating a mysql jdbc ConnectionConnection conn = DriverManager.getConnection(

    jdbc:mysql://localhost:3306/hibernate, root, root);

    Creating a jdbc Statement object

    * Statement * Prepared Statement * Callable Statement

    Executing a SQL statement with the Statement object, andreturning a jdbc resultSet.

  • 8/2/2019 Hibernate Training Day 1

    6/49

    CONFIDENTIAL

    ORM

  • 8/2/2019 Hibernate Training Day 1

    7/49

    Financial Services| Capital MarketsCONFIDENTIAL

    6

    Object relation mapping fundamentals

    Objects to integrate into Relational model

    Object modeling describes system through objects, Association, behavior, state, inheritance

    Relational modeling describes system through information. Relation, Attribute, Domain

    Object-relational mapping is the process of transforming between object and relational modelingapproaches

  • 8/2/2019 Hibernate Training Day 1

    8/49

    Financial Services| Capital MarketsCONFIDENTIAL

    7

    Object relation mapping - Advantages

    Natural programming model

    Reduced Line Of Code Code can be run / Tested out side the container

    Classes may be reused in non persistence context

    Minimum database access with smart fetching strategies

    Opportunities for aggressive caching

    Structural mapping more robust when Object/Relational data model changes.

  • 8/2/2019 Hibernate Training Day 1

    9/49

    CONFIDENTIAL

    Introduction to Hibernate

  • 8/2/2019 Hibernate Training Day 1

    10/49

    Financial Services| Capital MarketsCONFIDENTIAL

    9

    Why Hibernate ?

    Open sourcePersistence for java beans or POJO

    Relieves from manual ResultSet Handling

    Easy Switching to other SQL database

    Powerful queries

    Extensive RDBMS support

    Tools support

    Integrates elegently

  • 8/2/2019 Hibernate Training Day 1

    11/49

    Financial Services| Capital MarketsCONFIDENTIAL

    10

    RDBMS Support

    Hibernate is tested with wide range of databases.

    DB2 7.1, 7.2; MySQL 3.23;

    PostgreSQL 7.1.2, 7.2, 7.3;

    Oracle 8i, 9i;

    Sybase 12.5 (JConnect 5.5);

    Interbase 6.0.1 (Open Source)

    With Firebird InterClient 2.01;

    HypersonicSQL 1.61, 1.7.0;

    Microsoft SQL Server 2000;

    Mckoi SQL 0.93

    Progress 9

    Pointbase Embedded 4.3

    SAP DB 7.3

  • 8/2/2019 Hibernate Training Day 1

    12/49

    Financial Services| Capital MarketsCONFIDENTIAL

    11

    Tools Support

    Modeling tools / Code generator

    Middlegen

    AndroMDA

    XDoclet

    IDE Plug-in support:

    RSA, JBOSS, Eclipse WTP

  • 8/2/2019 Hibernate Training Day 1

    13/49

    Financial Services| Capital MarketsCONFIDENTIAL

    12

    Hibernate application components

    Hibernate Libraries

    Hibernate configuration file

    Hibernate mapping files (HBM files)

    POJO classes

    Main class

  • 8/2/2019 Hibernate Training Day 1

    14/49

    Financial Services| Capital MarketsCONFIDENTIAL

    13

    Hibernate Environment

    antlr.jar

    cglib.jarasm.jarasm-attrs.jarscommons-collections.jar

    commons-logging.jarhibernate3.jarjta.jardom4j.jar

    log4j.jar

  • 8/2/2019 Hibernate Training Day 1

    15/49

    Financial Services| Capital MarketsCONFIDENTIAL

    14

    First trip to Hibernate World

    Column | Type | Modifiers

    ----------+-----------------------+---------EMPID (PK) | int | not nullname | varchar(50) | not nullsalary | double |

    email | varchar(50) |

    Employee Java ObjectEmployee DB Table

  • 8/2/2019 Hibernate Training Day 1

    16/49

    Financial Services| Capital MarketsCONFIDENTIAL

    15

    First trip to Hibernate World

    Hibernate configuration property file

    Used for configuring hibernate Contains

    - Database Configuration- Datasource Configuration- Transaction Configuration- Caching Configuration

    - ConnectionPool Configuration- Other Settings.

  • 8/2/2019 Hibernate Training Day 1

    17/49

    Financial Services| Capital MarketsCONFIDENTIAL

    16

    First trip to Hibernate World

    Hibernate Configuration

    com.mysql.jdbc.Driverjdbc:mysql://localhost:3306/hibernaterootrootorg.hibernate.dialect.MySQLDialecttrueupdate

  • 8/2/2019 Hibernate Training Day 1

    18/49

    Financial Services| Capital MarketsCONFIDENTIAL

    17

    First trip to Hibernate World

    The hibernate-mapping configuration file

    Object to relation mappings are often defined in a xml file Mapping file can be hand written or edited. Java Centric persistence classes. No. of tools available to generate the configuration.

    -AndroMDA-XDoclets

    -Middlegen Standard DTD for correct implementation

  • 8/2/2019 Hibernate Training Day 1

    19/49

    Financial Services| Capital MarketsCONFIDENTIAL

    18

    First trip to Hibernate World

    Hibernate XML Configuration - Employee.hbm.xml

  • 8/2/2019 Hibernate Training Day 1

    20/49

    Financial Services| Capital MarketsCONFIDENTIAL

    19

    First trip to Hibernate World

    Persisting the Employee

    SessionFactory sf = Configuration.configure().buildSessionFactory();Session session = sf.OpenSession();Transaction tx = session.beginTransaction();

    Employee emp = new Employee()emp.setEmail(sadinenijayadev @yahoo.co.in);

    emp.setName(Jayadev S);emp.setSalary(13331);session.save(emp);

    Tx.commit();session.close();

  • 8/2/2019 Hibernate Training Day 1

    21/49

    Financial Services| Capital MarketsCONFIDENTIAL

    20

    First trip to Hibernate World

    Loading the Employee

    Try{SessionFactory sf = Configuration.configure().buildSessionFactory();Session session = sf.OpenSession();Transaction tx = session.beginTransaction();

    Employee emp = session.get(Employee.Class, new Long(1));

    System.out.println(Employee salary : + emp.getSalary());

    Tx.commit();

    }Catch(HibernateException e){e.printStackTrace();

    }

  • 8/2/2019 Hibernate Training Day 1

    22/49

    CONFIDENTIAL

    Hibernate Architecture

  • 8/2/2019 Hibernate Training Day 1

    23/49

    Financial Services| Capital MarketsCONFIDENTIAL

    22

    Hibernate Architecture

    Responsibilities of architecture

    -Manage connection with the database

    -Converts HQL (Hibernate Query Language)statements to database specific statement.

    -Manage result set on its own.

    -Performs mapping of these database specific

    data to Java objects which are directly used byJava application.

  • 8/2/2019 Hibernate Training Day 1

    24/49

    Financial Services| Capital MarketsCONFIDENTIAL

    23

    Hibernate Architecture Core Interfaces

    Hibernate Core interfaces

    SessionFactory Interface

    Hibernate Session provider

    Single instance per application/data source.

    Caches generated SQL statements and other mapping metadata.

    Session interface

    Hibernate session can be termed as a collection of loaded objects relating toa single unit of work.

    This Is the primary interface used by the Hibernate application.

    Hibernate Session are not thread safe hence by design be used one sessionper thread.

    Configuration Interface

    The Configuration object is used to configure and bootstrap Hibernate.

    Application uses Configuration instance to specify the location of mappingfiles.

  • 8/2/2019 Hibernate Training Day 1

    25/49

    Financial Services| Capital MarketsCONFIDENTIAL

    24

    Hibernate Architecture - Core Interfaces

    Transaction Interface

    The Transaction interface is an optional API. User might choose to use JDBC Tx, JTA

    Abstracts the application code by the underlying transaction implementations. Helps to keep hibernate application portable between different kind of execution environments.

    Query and Criteria Interfaces.

    Manages and controls query execution

    Queries can be written in HQL or in native SQL.

    Criteria interfaces allows you to create execute object oriented criteria queries.

    Callbackinterfaces

    Allow the application to receive notification when a transaction happens to an object. Eg. when the object is loaded,deleted, saved.

    Hibernate interfaces are not needed to be implemented but are useful sometimes.

    Types

    Extension Interfaces

    Interfaces that allow extension of Hibernates powerful mapping functionality, such as UserType,CompositeUserType, and IdentifierGenerator.

  • 8/2/2019 Hibernate Training Day 1

    26/49

    Financial Services| Capital MarketsCONFIDENTIAL

    25

    Hibernate Architecture - Elements

    General steps:

    /* Load the Hibernate configuration file and create configuration object. It willautomatically load all hbm mapping files. */

    Configuration cfg = new Configuration();

    cfg.configure(CONFIG_FILE_LOCATION);

    /* Create session factory from configuration object */

    SessionFactory sessionFactory = cfg.buildSessionFactory();

    /* Get one session from this session factory. */

    Session session = sessionFactory.openSession();

    /* Create HQL query. */Query query = session.createQuery("from EmployeeBean);

    /* Execute query to get list containing Java objects. */

    List finalList = query.list();

  • 8/2/2019 Hibernate Training Day 1

    27/49

    CONFIDENTIAL

    Hibernate Persistent ClassesNovember 24, 2008

  • 8/2/2019 Hibernate Training Day 1

    28/49

    Financial Services| Capital MarketsCONFIDENTIAL

    27

    Persistent classes

    Persistent classes are classes in an application that

    implement the entities of the business problemExamples:

    Employee

    Customer Order

    Item

    Hibernate persistent classes implement POJOfundamentals

    POJO Rules

  • 8/2/2019 Hibernate Training Day 1

    29/49

    Financial Services| Capital MarketsCONFIDENTIAL

    28

    POJO Rules

    Implement a no-argument constructor

    Required for runtime proxy generation using

    Constructor.newInstance()

    Constructor must have atleast package visibility

    Provide an identifier property (optional)

    Some functionalities (transitive persistence) require identifier

    Consistently-named

    Nullable (Non-primitive) type

    Prefer non-final classes (optional)

    Mandatory for proxying

    Performance tuning

    Declare accessors and mutators for persistent fields (optional)

    Can persist a property with default, protected or private get/set pair

    POJO l

  • 8/2/2019 Hibernate Training Day 1

    30/49

    Financial Services| Capital MarketsCONFIDENTIAL

    29

    POJO example

    public class Parent implements Serializable { //Implements serializable

    private long id; //Identifier property

    private Set child;

    public Parent() {} //No arg constructor

    public String getId() { //Accessor methods

    return id;

    }

    public void setId(long id) {

    this.id = id;}

    public Set getChild() {

    return child;

    }

    public void setChild(Set child) {

    this.child =child;

    . //Some Logic}

    public MonetaryDetails calcInvestment (Child child) {

    ... //Business method

    }

    }

    POJO R l

  • 8/2/2019 Hibernate Training Day 1

    31/49

    Financial Services| Capital MarketsCONFIDENTIAL

    30

    POJO Rules

    Implement equals & hashCode() methods

    Hibernate guarantees equivalence of objects only insession scope

    Necessary for scenarios where instances are stored in a

    Set or are reattached to the session Necessary for the problem with differences between

    object identity in the virtual machine (VM) and objectidentity in the database.

    POJO Rules Example

  • 8/2/2019 Hibernate Training Day 1

    32/49

    Financial Services| Capital MarketsCONFIDENTIAL

    31

    POJO Rules Example

    public class User {

    ...

    public boolean equals(Object obj) {

    if (obj == null) return false;

    if (obj == this) return true;

    if (obj.getClass() != getClass()) return false;

    Child child = (Child) obj;

    if (this.getFirstName().equals(child.getFirstName())

    && this.getLastName().equals(child.getLastName())) {

    return true;

    }

    return false;

    }

    public int hashCode() {int tmp = 0;

    tmp = (firstName +lastName).hashCode();

    return tmp;

    }

    }

    i t th d

  • 8/2/2019 Hibernate Training Day 1

    33/49

    Financial Services| Capital Markets

    persistence methods

    The following are the methods used to write the object tothe database:

    save()

    persist()

    update()

    saveOrUpdate()

    merge()

    Example

  • 8/2/2019 Hibernate Training Day 1

    34/49

    Financial Services| Capital Markets

    Example

    Example using Persistence methods.

    PersistenceManage manage= new PersistenceManage();

    Session session = HibernateUtil.currentSession();Transaction t = session.beginTransaction();

    Singer singer = new Singer ();

    manage.saveSinger(singer, session);

    manage.persistSinger(singer, session);

    manage.saveUpdateSinger(singer, session);manage.mergeSinger(singer, session);

    if (session != null && session.isOpen()) {

    if(t.isActive()) {

    t.commit();

    HibernateUtil.closeSession();

    }

    }

  • 8/2/2019 Hibernate Training Day 1

    35/49

    CONFIDENTIAL

    Working with objects

    Wh t i T i t Obj t?

  • 8/2/2019 Hibernate Training Day 1

    36/49

    Financial Services| Capital Markets

    What is a Transient Object?

    I want to insert a new User into the database!!!

    Create a new User object

    Employee newEmp = new Employee();

    newEmp.setUserName(JOHN);

    newEmp.setEmailId([email protected]);

    All work described was performed by Capgemini or a Capgemini affiliate

    35

    Wh t i i t t Obj t?

  • 8/2/2019 Hibernate Training Day 1

    37/49

    Financial Services| Capital Markets

    What is persistent Object?

    Obtain session object and save newEmp

    SessionFactory sf = Configuration.configure().buildSessionFactory();

    Session session = sf.OpenSession();

    Transaction tx = session.beginTransaction();

    session.save(newEmp);

    System.out.println(newEmp.getId());

    tx.commit();

    session.close();

    All work described was performed by Capgemini or a Capgemini affiliate

    36

    What is a detached object?

  • 8/2/2019 Hibernate Training Day 1

    38/49

    Financial Services| Capital Markets

    What is a detached object?

    After the session is closed, I want the id.

    System.out.println(newEmp.getId());

    All work described was performed by Capgemini or a Capgemini affiliate

    37

    Persistence Lifecycle

  • 8/2/2019 Hibernate Training Day 1

    39/49

    Financial Services| Capital Markets

    Persistence Lifecycle

    All work described was performed by Capgemini or a Capgemini affiliate

    38

    Transient objects

  • 8/2/2019 Hibernate Training Day 1

    40/49

    Financial Services| Capital Markets

    Transient objects

    Not associated with database, table or row

    If not referenced, they are inaccessible and valid forgarbage collection

    They are non-transactional

    To convert transient object to persistent object

    Call to save() or saveOrUpdate()

    creation of a reference from an already persistent

    instance.

    All work described was performed by Capgemini or a Capgemini affiliate

    39

    Persistent Objects

  • 8/2/2019 Hibernate Training Day 1

    41/49

    Financial Services| Capital Markets

    Persistent Objects

    Any instance with a database identity

    Associated with a Session and are transactional

    State is synchronized with the database at variousinstances and changes are propagated

    Automatic Dirty Checking

    Call to delete() makes a persistent object transient.

    All work described was performed by Capgemini or a Capgemini affiliate

    40

    Detached Objects

  • 8/2/2019 Hibernate Training Day 1

    42/49

    Financial Services| Capital Markets

    Detached Objects

    Instances lose their association with persistence managerwhen session is closed

    They contain persistent data (which might be stale later)

    State is no longer guaranteed to be synchronized with db

    state Can be re-associated with a session again using

    session.lock()

    Explicit detachment operation is also provided by

    hibernate, Session.evict()

    All work described was performed by Capgemini or a Capgemini affiliate

    41

    Update persistent state of detached object

  • 8/2/2019 Hibernate Training Day 1

    43/49

    Financial Services| Capital Markets

    Update persistent state of detached object

    Employee emp1 = new Employee();

    Transaction tx1 = sess.beginTransaction();

    emp1.setName(name);emp1.setSalary(sal);

    emp1.setEmail(email);

    sess.save(emp1);

    tx1.commit();

    sess.close();

    //Without forcing an update

    Session sessionTwo = HibernateUtil.currentSession();

    Transaction tx2 = sessionTwo.beginTransaction();

    sessionTwo.lock(emp1, LockMode.NONE);

    emp1.setName(Good Man");

    emp1.setEmail ([email protected]");

    tx2.commit();

    sessionTwo.close();

    All work described was performed by Capgemini or a Capgemini affiliate

    42

    Retrieving a persistent object

  • 8/2/2019 Hibernate Training Day 1

    44/49

    Financial Services| Capital Markets

    Retrieving a persistent object

    Session.load()

    //Get the object with a given identifier

    long id = 1

    Employee emp = (Employee) session.load(Employee.class, new Long(id));

    //Load state of employee in a new object of your own

    Employee newEmp = new Employee ();

    Session.load(newEmp, new Long(id));

    Used when a row with given identifier definitely exist in database

    All work described was performed by Capgemini or a Capgemini affiliate

    43

    Retrieving a persistent object

  • 8/2/2019 Hibernate Training Day 1

    45/49

    Financial Services| Capital Markets

    Retrieving a persistent object

    Session.get()

    //Get the object with a given identifier

    long id = 1

    Employee user = (Employee) session.get(Employee.class, new Long(id));

    Used when we are not sure that a row with given identifier exist in the database

    Returns null if row doesnt exist

    All work described was performed by Capgemini or a Capgemini affiliate

    44

    Re loading persistent object

  • 8/2/2019 Hibernate Training Day 1

    46/49

    Financial Services| Capital Markets

    Re-loading persistent object

    session.refresh();

    sess.save(emp);

    sess.flush(); //force the SQL INSERT

    sess.refresh(emp);

    Generally used when database triggers are used to initialize some of the properties ofan object

    Loads the object, synchronizes with the DB.

    All work described was performed by Capgemini or a Capgemini affiliate

    45

    Making objects Transient

  • 8/2/2019 Hibernate Training Day 1

    47/49

    Financial Services| Capital Markets

    g j

    //Making Persistent Object Transient

    Session session = sessions.openSession();

    Transaction tx = session.beginTransaction();int userID = 1234;

    Employee emp = (Employee) session.get(Employee.class, new Long(userID)); // emp is

    //in persistent state

    session.delete(emp); //emp moved to transient state

    tx.commit();

    session.close();

    //Making Detached Object Transients

    session.save(emp);

    session.close();

    Emp = new Employee(); //or we need to make the detached to the Persistent then delete

    Session session2 = sessions.openSession();

    session2.delete(emp);

    All work described was performed by Capgemini or a Capgemini affiliate

    46

    Flushing Session

  • 8/2/2019 Hibernate Training Day 1

    48/49

    Financial Services| Capital Markets

    Flushing Session

    session.flush()

    Session will execute the SQL statements needed to synchronize the JDBC

    connections state with the state of objects held in memory.

    Executed at following points:

    before some query executions

    from org.hibernate.Transaction getting committed.

    from Session.flush() calling explicitly

    SQL fired in following order

    all entity insertions, in the same order the corresponding objects were saved using Session.save()

    all entity updates

    all collection element deletions, updates and insertions

    all entity deletions, in the same order the corresponding objects were deleted using Session.delete()

    All work described was performed by Capgemini or a Capgemini affiliate

    47

  • 8/2/2019 Hibernate Training Day 1

    49/49

    Break