Subscribe Us

The Hibernate Technology

Agenda


  • 1. INTRODUCTION

    1.1 OBJECT RELATIONAL MAPPING (ORM)
    1.2 HIBERNATE
    1.3 WHY HIBERNATE?
    1.4 HIBERNATE VS. JDBC

  • 2. ABOUT POJO
    2.1 EXAMPLE OF POJO
  • 3. HIBERNATE ARCHITECTURE
  • 4. CONFIGURATION
    4.1 SOFTWARE AND TOOLS REQUIREMENTS
    4.2 SUPPORTED DATABASE IN HIBERNATE
    4.3 VERSION COMPARISON MATRIX
    4.4 CONFIGURATION STEPS…

  • 5. HQL : THE HIBERNATE QUERY LANGUAGE
  • 6. EXAMPLE OF HIBERNATE
  • 7. RESULT
  • 8. ADVANTAGES
  • 9. DISADVANTAGE
  • 10. HIBERNATE 4.0
  • 11. HIBERNATE VS. OTHERS

    1. Introduction


    1.1 Object Relational Mapping (ORM):
    The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model.


  • A complete ORM solution should provide:
    - Basic CRUD functionality
    - An Object-Oriented Query Facility
    - Mapping Metadata support
    - Transactional Capability'


  • Various ORM products include:
    - Apache DB Project
    ­- Sybase, Inc.
    ­- Hibernate
    ­- Sample ORM

    Why Object Relational Mapping (ORM)?
  • Productivity (reduce development time)
  • Maintainability (minimize effects between the object and the relational model when changes)
  • Performance (major bottlenecks are removed for a wide variety of database)
  • Vendor independence (much easier to develop a cross-platform application)

    1.2 Hibernate
  • Hibernate is a free, open source Java package that makes it easy to work with relational databases.
  • 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.
  • Hibernates goal is to relieve the developer from 95 percent of common data persistence related programming tasks.
  • 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.
  • It uses POJO objects (Plain Old Java Objects).

    1.3 Why Hibernate?
    1) Relational Persistence for JAVA :
    Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there is mismatch between how data is represented in objects versus relational database. So with JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.

    2) Transparent Persistence :
    The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. With JDBC this conversion is to be taken care of by the developer manually with lines of code.

    3) Support for Query Language :
    JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries.

    4) Database Dependent Code
    Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties.

    5) Optimize Performance :
    Caching is retention of data, usually in application to reduce disk access. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many - 8 - times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. With JDBC, caching is maintained by hand coding.

    6) Open-Source, Zero-Cost Product License :
    Hibernate is an open source and free to use for both development and production deployments.

    7) Enterprise-Class Reliability and Scalability :
    Hibernate scales well in any environment, no matter if use it in-house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands.

    1.4 Hibernate Vs. JDBC



    2. About POJO (Plain Old Java Object )


    In our ideal world, it would be trivial to take any Java object and persist it to the database. No special coding would be required to achieve this, no performance penalty would ensue, and the result would be totally portable. In this ideal world, we would perhaps perform such an operation in a manner like that shown in below.

    2.1 Sample POJO
    SessionFactory factory = config.buildSessionFactory();
    Session session = factory.openSession();
    org.hibernate.Transaction tx = session.getTransaction();
      
    tx.begin();
    Dvddetails d1 = new Dvddetails();
    d1.setDvdGener(gener);
    d1.setDvdTitle(title);
    d1.setDvdYear(year);
    session.save(d1);
    tx.commit();
    
    

  • The POJO with mapping annotations :
    package com.dvdlibrary;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    @Entity
    public class Dvddetails {
     private String dvdYear;
     private String dvdTitle;
     private String dvdGener;
     public String getDvdYear() {
      return dvdYear;
     }
     public void setDvdYear(String dvdYear) {
      this.dvdYear = dvdYear;
     }
     @Id
     public String getDvdTitle() {
      return dvdTitle;
     }
     public void setDvdTitle(String dvdTitle) {
      this.dvdTitle = dvdTitle;
     }
    public String getDvdGener() {
      return dvdGener;
     }
     public void setDvdGener(String dvdGener) {this.dvdGener = dvdGener;
    }
    }
    
    

  • Mappings :
    Hibernate needs something to tell it which tables relate to which objects. In Hibernate parlance, this is called a mapping. Mappings can either be provided through Java annotations, or through an XML mapping file. using annotations, as we can mark up the POJO Java classes directly. if we are satisfied with the default values that Hibernate provides for us, we do not need to explicitly provide them as annotations. For instance, Hibernate uses the name of the POJO class as the default value of the database table the object maps to. In our example, if we are satisfied with using a database table named message, we do not need to define it in the source code.


  • Xml mapping Example :


    Save this mapping file as src/main/resources/org/hibernate/tutorial/domain/

    Dvddetails.hbm.xml.

    Now that we have our POJOs, we need to map them to the database, representing the fields of each directly or indirectly as values in the columns of the associated tables. We take each in turn, starting with the User class. The first step is to tell Hibernate to map the class with the @Entity annotation. We also need to tell Hibernate that we would like the database table that stores the Dvddetails. The next step is to map the fields on the class. The User class has three fields, as follows: The id field: Corresponds to the surrogate key to be used in, and generated by, the database. This special field is handled by the @Id annotation. We specify that it should be generated by the database, rather than by the application, by using the @GeneratedValue annotation. Is use for auto generation value for primary key.we can also specify our own table name using @Table(name=”table name”) annotation & also column name like @Column(name=”column name”). if we want to create a primary key we add annotation @id and @GeneratedValue annotation for auto generated value. For creating a uniq key add @Cloumn(unique=trye) annotation suppose we have a many to many or one to many relation then we use a @manytomary and @onetomany annotation respectively then set a @jointable(name=”tablename”) for relation ship we also add cascading effect using cascade property in jointable annotation.


  • Basic value types :
    The built-in basic mapping types can be roughly categorized into the following:
    integer, long, short, float, double, character, byte, boolean, yes_no, true_false Type mappings from Java primitives or wrapper classes to appropriate (vendor-specific) SQLcolumn types. boolean, yes_no and true_false are all alternative encodings for a Java boolean or java.lang.Boolean.
    string :
    A type mapping from java.lang.String to VARCHAR (or Oracle VARCHAR2).

    date, time, timestamp :
    Type mappings from java.util.Date and its subclasses to SQL types DATE, TIME and TIMESTAMP (or equivalent).

    calendar, calendar_date :
    Type mappings from java.util.Calendar to SQL types TIMESTAMP and DATE (or equivalent).

    big_decimal, big_integer :
    Type mappings from java.math.BigDecimal and java.math.BigInteger to NUMERIC (or Oracle NUMBER).

    locale, timezone, currency :
    Type mappings from java.util.Locale, java.util.TimeZone and java.util.Currency to VARCHAR (or Oracle VARCHAR2). Instances of Locale and Currency are mapped to their ISO codes. Instances of TimeZone are mapped to their ID.
    class
    A type mapping from java.lang.Class to VARCHAR (or Oracle VARCHAR2). A Class is mapped to its fully qualified name.

    binary :
    Maps byte arrays to an appropriate SQL binary type.

    text :
    Maps long Java strings to a SQL LONGVARCHAR or TEXT type.

    image :
    Maps long byte arrays to a SQL LONGVARBINARY.

    serializable :
    Maps serializable Java types to an appropriate SQL binary type. You can also indicate the Hibernate type serializable with the name of a serializable Java class or interface that does not default to a basic type.


  • Making objects persistent :
    We can make a transient instance persistent by associating it with a session for ex:
    AnnotationConfiguration config = new AnnotationConfiguration();
    config.addAnnotatedClass(Dvddetails.class);
    config.configure("hibernate.cfg.xml");
    new SchemaExport(config).create(true, true);
    SessionFactory factory = config.buildSessionFactory();
    SessionFactory factory = config.buildSessionFactory();
    Session session = session.getCurrentSession();
    session.beginSession();
      
    Dvddetails d1 = new Dvddetails();
    d1.setDvdGener(gener);
    d1.setDvdTitle(title);
    d1.setDvdYear(year);
    
    session.save(d1);
    session.getTransaction.commit();
    
    

    Hibernate comes remarkably close to this, at least when compared with the alternatives—but alas, there are configuration files to create and subtle performance issues to consider. Hibernate does, however, achieve its fundamental aim—it allows you to store POJOs in the database. Following Figure shows how Hibernate fits into your application between the client code and the database :


    3. Hibernate Architecture


    The diagram below provides a high-level view of the Hibernate architecture: The diagram below provides a high-level view of the Hibernate architecture:

  • It creates a layer between Database and the Application. It loads the configuration details like Database connection string, entity classes, mappings etc.
  • Hibernate creates persistent objects which synchronize data between application and database.

    Minimal architecture

    The above diagram shows a comprehensive architecture of Hibernate. In order to persist data to a database, Hibernate create an instance of entity class (Java class mapped with database table).
    This object is called Transient object as they are not yet associated with the session or not yet persisted to a database. To persist the object to database, the instance of SessionFactory interface is created.

    SessionFactory is a singleton instance which implements Factory design pattern.
    SessionFactory loads hibernate.cfg.xml file (Hibernate configuration file.

    More details in following section) and with the help of Transaction Factory and Connection Provider implements all the configuration settings on a database.
    Each database connection in Hibernate is created by creating an instance of Session interface. Session represents a single connection with database. Session objects are created from SessionFactory object.
    Hibernate also provides built-in Transaction APIs which abstracts away the application from underlying JDBC or JTA transaction. Each transaction represents a single atomic unit of work. One Session can span through multiple transactions.

    SessionFactory (org.hibernate.SessionFactory):
    A thread-safe, immutable cache of compiled mappings for a single database. A factory for org.hibernate.Session instances. A client of org.hibernate.connection.ConnectionProvider. Optionally maintains a second level cache of data that is reusable between transactions at a process or cluster level.

    Session (org.hibernate.Session)
    A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC java.sql.Connection. Factory for org.hibernate.Transaction. Maintains a first level cache of persistent the application’s persistent objects and collections

    Persistent objects and collections :
    Short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one org.hibernate.Session. Once the org.hibernate.Session is closed, they will be detached and free to use in any application layer (for example, directly as data transfer objects to and from presentation).

    Transient and detached objects and collections :
    Instances of persistent classes that are not currently associated with a org.hibernate.Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed org.hibernate.Session.

    Transaction (org.hibernate.Transaction):
    (Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A org.hibernate.Session might span several org.hibernate.Transactions in some cases. However, transaction demarcation, either using the underlying API or org.hibernate.Transaction, is never optional.

    ConnectionProvider (org.hibernate.connection.ConnectionProvider):
    (Optional) A factory for, and pool of, JDBC connections. It abstracts the application from underlying javax.sql.DataSource or java.sql.DriverManager. It is not exposed to application, but it can be extended and/or implemented by the developer.

    TransactionFactory (org.hibernate.TransactionFactory):
    (Optional) A factory for org.hibernate.Transaction instances. It is not exposed to the application, but it can be extended and/or implemented by the developer.

    4. Configuration


    4.1. Software and Tools Requirements
    1. Java Development kit
    2. Eclipse Galileo
    3. db-derby
  • Db-derby is database provided by apache.
    4. Hibernate
  • hibernate-distribution 3.3.2
  • hibernate-annotations-3.4.0

    Link for above Software
    1. JDK(Java Development Kit)
    http://www.oracle.com/technetwork/java/javaee/downloads/
    2. Eclipse-jee-galileo-SR2-win32.zip
    http://www.eclipse.org/downloads/packages/release/galileo/r
    download java EE IDE
    3. db-derby-10.6.1.0-bin.zip or latest
    http://db.apache.org/derby/derby_downloads.html
    10.6.1.0 link below click
    4. Hibernate-annotations-3.4.0.GA.zip
    http://sourceforge.net/projects/hibernate/files/hibernate-annotations/3.4.0.GA/hibernate-annotations-3.4.0.GA.zip/download

    4.2. Supported Databases and Dialect Class Names for Hibernate 3.5


    4.3. VERSION COMPARISON


  • Bird Eye

    4.4. Configuration Steps
    1) Eclipse Settings
    1) Start eclipse
    2) set workspace ( c:\hibernatelessions\code)
    3) file–new–others–java project–project name(hibernateExample)-finish.

    2) Database Setup
    1) Go to downloads
    2) Db-derby-10.6.1.0-bin.
    3) Bin
    4) startnetworkserver.bat

    3) Database connection
    1) eclipse
    2) window
    3) open perspective
    4) other
    5) database Development
    6) press ok
    7) right click database connection
    8) new
    9) select Derby
    10) give connection name( HibernateConnection)
    11) ok
    12) click new drover definition
    13) select Derby Client JDBC Driver
    14) Goto Jar list tab
    15) click add jar/zip
    16) c:\OS\hibernatelessions\downloads\db-derby-10.6.1.0-bin\lib\derbyclient.jar
    17) remove unwanted jar files
    18) goto permissions tab
    19) Copy connection URL
    20) paste into notepad
    21) copy driver class & paste into notepad
    22) close
    23) set database name(HibernateDb)
    24) set username, password & test connection
    25) copy connection url and paste & replace in notepad
    26) ok

  • Adding a Hibernate 3.0 User Define Library
    1) window
    2) preferences
    3) search user libraries
    4) new
    5) user library name(Hibernate 3.0)
    6) ok
    7) add jars
    8) c:\OS\hibernatelessions\downloads\db-derby-10.6.1.0-bin\lib\derbyclient.jar
    9) c:\OS\hibernatelessions\downloads\hibernate-dsistribution-3.3.2.GA
    10) hibernate3.jar select
    11) open
    12) add jars
    13) c:\OS\hibernatelessions\downloads\hibernate-dsistribution-3.3.2.GA\lib\required\select all open
    14) c:\OS\hibernatelessions\downloads\hibernate-dsistribution-3.3.2.GA\lib\bytecode\cglib\cglib-2.2.jar
    15) c:\OS\hibernatelessions\downloads\hibernate-annotation-3.4.0.GA\hibernate-annotation.jar open
    16) c:\OS\hibernatelessions\downloads\hibernate-annotation-3.4.0.GA\lib\ejb3-persistence.jar
    17) c:\OS\hibernatelessions\downloads\hibernate-annotation-3.4.0.GA\lib\hibernate-commons-annotations.jar
    18) c:\OS\hibernatelessions\downloads\hibernate-annotation-3.4.0.GA\lib\test\slf4j- log4j12.jar
    19) c:\OS\hibernatelessions\downloads\hibernate-annotation-3.4.0.GA\lib\test\log4j.jar
    20) right click on project
    21) select properites
    22) select java build path
    23) libraries tab
    24) add library
    25) select User Library
    26) next
    27) check hibernate 3.0
    28) finish
    29) ok
    30) c:\OS\hibernatelessions\downloads\hibernate-dsistribution-3.3.2.GA\project\tutorials\web\src\main\resources\
    31) copy hibernate.cfg.xml & log4j.properties
    32) Paste in src of project


  • Settings of hibernate.cfg.xml file
    1) open hibernate.cfg.xml
    2) select source
    3) open windows-preferences
    4) open notepad file
    5) copy 2nd line
    6) paste in hibernate.cfg.xml
    7) paste & replace 2nd line
    8) set connection.url
    9) set username & password
    10) check save
    11) set - Dialect to org.hibernate.dialect.DerbyDialect
    12) save
    13) set current_session_context_class - thread
    14) comment "Drop and re-create the database schema on start up"
    15) Eclipse


  • Connecting database
    16) database connection
    17) HibernateConnection- right click- connect
    18) top right arrow (>>) select J2EE

  • Library File Collections..

  • Directory Structure of Hibernate


    WHAT IS TO BE DONE…

    1. Identify the POJOs that have a database representation.
    2. Identify which properties of those POJOs need to be persisted.
    3. Annotate each of the POJOs to map your Java object's properties to columns in
    a database table (Shown below).
    4. Create the database schema using the schema export tool, use an existing
    database, or create your own database schema.
    5. Add the Hibernate Java libraries to your application’s classpath
    6. Create a Hibernate XML configuration file that points to your database and your mapped classes
    7. create a Hibernate Configuration object that references your XML configuration file
    8. build a Hibernate SessionFactory object from
    9. Finally, retrieve Hibernate Session objects from the SessionFactory, and write data access logic in application (create, retrieve, update, and delete).

  • CONFIGURATION FILE

    Hibernate will be connecting to the database on behalf of your application, so it needs to know how to obtain connections. For Hibernate's configuration, we can use a simple hibernate.properties file, a more sophisticated hibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file:


    5. HQL: The Hibernate Query Language


    Hibernate uses a powerful query language (HQL) that is similar in appearance to SQL. Compared with SQL, however, HQL is fully object-oriented and understands notions like inheritance, polymorphism and association.

  • Case Sensitivity :
    Queries are case sensitive because of exception of names of java classes and properties. So SeLeCt is same as sElEcT is same as SELECT. Queries in uppercase is not suitable for java language.

  • The from clause :
    The simplest form of from clause is :
    from eg.Cat

    it is not necessary that you use a class name every time. from Cat

  • Associations and joins :
    You can also assign aliases to associated entities using a join.

    For example, from Cat as cat
    inner join cat.mate as mate
    left outer join cat.kittens as kitten

  • The supported joins borrowed from ANSI SQL :
    1. Inner join
    2. Outer join
    3. Full join
    A ‘fetch’ join is use to let associations of data to be initialized with a single select.
    For example, from Cat as cat inner join fetch cat.mate


  • Forms of join syntax :
    HQL supports two types of joins : implicit and explicit
    The implicit form does not use the join keyword. Instead, associations are dereferenced by a dot notation.implicit joins can appear in any of the HQL clauses.

    For example, fetch Cat as cat where cate.mate.name like %s%


  • The select clause :
    The query clause fetch data from database and sends it into query objects.

    For example, select Cat.mate from Cat cat

  • Aggregate functions :
    HQL queries can even return the result of aggregate function.
    For example, select weight(cat.weight) from Cat cat

  • The supported aggregate functions are :

     avg(...), sum(...), min(...), max(...)
     count(*)
     count(...), count(distinct ...), count(all...)

    We can also use arithmetic operators, concatenation and recognized
    SQL functions in the select clause.

    For example, select cat.weight + sum(kitten.weight) from Cat cat
    The distinct and all keywords can be used as it has the same semantics in SQL.

  • Polymorphic queries :
    For example, a query like, from DVD as dvd
    Not only returns an instance of cat but also of subclasses like DvdLocal. Query will return instances of all persistent classes that extend the class or implement an interface.

  • The where clause :
    The where clause allows you to refine objects those are returned. If no alias exist, then you can refer to property name.
    For example, from Dvd where name=”abc”

  • Expressions used with the where clause are following :
    1. Mathematical operators: +, -, *, /
    2. Binary comparison operators: <, >, <=, >=, =, !=, like
    3. Logical operators : and, or, not
    4. “simple case”, case… when… then… else… end.
    5. Any function defined by EJB-QL : substring(), trim(), lower(), upper(), length(), locate(), abs(), sqrt().
    6. Str() for converting numeric or temporal values to a readable string.
    7. The HQL index() function, that applies to aliases of a joined index collection.
    8. HQL functions like size(), minelement(), maxelement(), minindex(), maxindex().
    9. Any database supported SQL scaler functions like, sign(), trunc(),rtrim() and sin().


  • The order by clause :
    The result returned by a query can be ordered by a property of a class.
    For example, select name from Dvd orderby Genre
    There are two options like asc and desc for arranging result in an ascending or descending order.

  • The group by clause :
    The query resulting in aggregate values can be grouped together by any property of a class.

    For example, select title from dvd group by year

    By the way, the having clause is also available.
    For example, select title from dvd group by year having title like=%d%

  • Subqueries :
    Hibernate supports subqueries within queries
    For example, from dvd where year = 2009 (select year from dvd)

    6. SERVLET Example :

    package com.dvdlibrary;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.classic.Session;
    import org.hibernate.tool.hbm2ddl.SchemaExport;
    
    public class addDvd {
    // public static void main(String[] args) {
     public static void add(String title,String year,String gener){
      AnnotationConfiguration config = new AnnotationConfiguration();
      config.addAnnotatedClass(Dvddetails.class);
      config.configure("hibernate.cfg.xml");
      //new SchemaExport(config).create(true, true);
      SessionFactory factory = config.buildSessionFactory();
      Session session = session.getCurrentSession();
      session.beginSession();
      
      Dvddetails d1 = new Dvddetails();
      d1.setDvdGener(gener);
      d1.setDvdTitle(title);
      d1.setDvdYear(year);
    session.save(d1);
      session.getTransaction.commit();
    }
     }
    
    

  • Class & Object Explanataion:
    AnnotationConfiguration class : which is used for create a configuration mapping.

    config.addAnnotatedClass(Dvddetails.class); which add a pojo object that is store a permanently in a database.

    SessionFactory: that extract a details from hibernate.cfg.xml file tags property and map a database link with a class. It contain a session that used to make a transaction. the SessionFactory would normally be created elsewhere and made available to the application as a Java Native Directory Interface (JNDI) resource.

    Session: Hibernate Session objects from the SessionFactory, and write your data access logic in application for create, retrieve, update, and delete object from the tables. Like to sace object session.save(d1);

  • SERVLET Example :
    package com.dvdlibrary;
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class adddvdservlet extends HttpServlet {
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String title = request.getParameter("Title");
      String dvdyear = request.getParameter("Year");
      String gener;
      gener = request.getParameter("Genre");
      if(gener.equalsIgnoreCase("select")) 
       gener = request.getParameter("Genre1");
      try
      {
       addDvd.add(title, dvdyear, gener);
      }
    catch (Exception e) {
       System.out.println("error" + e);
      }
      response.sendRedirect("addsuccessdvd.jsp");
     }
    }
    
    


  • DVD LIBRARY CODE :

    ADD DVD :
    package com.dvdlibrary;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.classic.Session;
    public class addDvd {
     public static void add(String title, String year, String gener) {
      AnnotationConfiguration config = new AnnotationConfiguration();
      GlobalVariable.setConfig(config);
      config.addAnnotatedClass(Dvddetails.class);
      // new SchemaExport(config).create(true, true);
      SessionFactory factory = config.buildSessionFactory();
      Session session = factory.openSession();
      org.hibernate.Transaction tx = session.getTransaction();
      tx.begin();
      Dvddetails d1 = new Dvddetails();
      d1.setDvdGener(gener);
      d1.setDvdTitle(title);
      d1.setDvdYear(year);
      session.save(d1);
      tx.commit();
     }
    }
    

    GLOBAL VARIABLE :
    package com.dvdlibrary;
    import org.hibernate.cfg.AnnotationConfiguration;
    public class GlobalVariable {
     private static String dbconfig;
     public static void setConfig(AnnotationConfiguration config)
     {
      config.configure(dbconfig);
     }
     public static void setDatabase(String string) {
      dbconfig = string;
     }
    }
    

    ADD DVD SERVLET:
    package com.dvdlibrary;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    public class adddvdservlet extends HttpServlet {
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      HttpSession session = request.getSession(true);
      PrintWriter out = response.getWriter();
      response.setContentType("text/html");
      if(session.getAttribute("config")==null)
       response.sendRedirect("error.jsp");
      else
      {   
       String title = request.getParameter("Title");
       String dvdyear = request.getParameter("Year");
       String gener;
       gener = request.getParameter("Genre");
       if(gener.equalsIgnoreCase("select")) 
        gener = request.getParameter("Genre1");
       try
       {
        addDvd.add(title, dvdyear, gener);
       }
       catch (Exception e) {
        System.out.println("error" + e);
       }
       response.sendRedirect("addsuccessdvd.jsp");
      }
     }
    }
    

    DELETE DVD:
    package com.dvdlibrary;
    import org.hibernate.Query;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.classic.Session;
    public class deleteDvd {
     public static int deleteDvdByTitle(String args) {
      AnnotationConfiguration config = new AnnotationConfiguration();
      GlobalVariable.setConfig(config);
      config.addAnnotatedClass(Dvddetails.class);
      SessionFactory factory = config.buildSessionFactory();
      Session session = factory.getCurrentSession();
      session.beginTransaction();
      Query query = session
        .createQuery("delete Dvddetails where dvdTitle = :dvdTitle");
      query.setParameter("dvdTitle", args);
      int result = query.executeUpdate();
      session.getTransaction().commit();
      return result;
     }
    }
    

    DELETE DVD SERVLET:
    package com.dvdlibrary;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    public class deleteDvdservlet extends HttpServlet {
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String title = request.getParameter("Title");
      HttpSession session = request.getSession(true);
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      response.setContentType("text/html");
      if(session.getAttribute("config")==null)
       response.sendRedirect("error.jsp");
      else
      {
       if ( deleteDvd.deleteDvdByTitle(title)!=1)
        response.sendRedirect("deleteunsuccess.jsp");
       else
        response.sendRedirect("deletesuccess.jsp");
      }
     }
    }
    

    LIST DVD
    package com.dvdlibrary;
    import java.util.List;
    import org.hibernate.Query;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.classic.Session;
    public class getDvdlist {
     public static List getlist() {
      AnnotationConfiguration config = new AnnotationConfiguration();
      GlobalVariable.setConfig(config);
      config.addAnnotatedClass(Dvddetails.class);
      SessionFactory factory = config.buildSessionFactory();
      Session session = factory.getCurrentSession();
      session.beginTransaction();
      Query query = session.createQuery("from Dvddetails");
      List list = query.list();
      session.getTransaction().commit();
      return list;
     }
    }
    
    

    DVD DETAILS :
    package com.dvdlibrary;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    @Entity
    public class Dvddetails {
     private String dvdYear;
     private String dvdTitle;
     private String dvdGener;
     public Dvddetails(){}
     public Dvddetails(Dvddetails d)
     {
      this.dvdTitle = d.dvdTitle;
      this.dvdGener = d.dvdGener;
      this.dvdYear = d.dvdYear;
     }
     public String getDvdYear() {
      return dvdYear;
     }
     public void setDvdYear(String dvdYear) {
      this.dvdYear = dvdYear;
     }
     @Id
     public String getDvdTitle() {
      return dvdTitle;
     }
     public void setDvdTitle(String dvdTitle) {
      this.dvdTitle = dvdTitle;
     }
     public String getDvdGener() {
      return dvdGener;
     }
     public void setDvdGener(String dvdGener) {
      this.dvdGener = dvdGener;
     }
    }
    

    COPY DATABASE :
    package com.dvdlibrary;
    import java.util.List;
    
    import org.hibernate.Query;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.classic.Session;
    import org.hibernate.tool.hbm2ddl.SchemaExport;
    public class CopyDatabase {
     public static void main(String args1,String args2) {
      AnnotationConfiguration config = new AnnotationConfiguration();
      config.addAnnotatedClass(Dvddetails.class);
      config.configure(args1);
      SessionFactory factory = config.buildSessionFactory();
      Session session = factory.getCurrentSession();
      session.beginTransaction();
     
      AnnotationConfiguration configmysql = new AnnotationConfiguration();
      configmysql.addAnnotatedClass(Dvddetails.class);
      configmysql.configure(args2);
      new SchemaExport(configmysql).create(true, true);
      SessionFactory factorymysql = configmysql.buildSessionFactory();
      Session sessionmysql = factorymysql.getCurrentSession();
      sessionmysql.beginTransaction();
      
      Query query = session.createQuery("from Dvddetails");
      List list = query.list();
      session.getTransaction().commit();
      sessionmysql.beginTransaction();
      int i=0;  
      for(i1=0;i1list.size();i1++)
      {
       sessionmysql.save(new Dvddetails(list.get(i1)));
      }
      sessionmysql.getTransaction().commit();
    
     }
    
    }
    


    SWITCH DATABASE
    package com.dvdlibrary;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    public class setDatabase extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      boolean error = false;
      try
      {
       HttpSession session = request.getSession(true);
       PrintWriter out = response.getWriter();
       String filename = request.getParameter("database");
       String dbname = "";
       session.setAttribute("config", filename);
       if( filename.equalsIgnoreCase("hibernate.cfg.xml"))
         dbname = "DB Derby";
       else if (filename.equalsIgnoreCase("hibernatesql.cfg.xml"))
        dbname = "My Sql";
       else
        dbname = "Un Known";
       session.setAttribute("dbname", dbname );
       String s = request.getParameter("database");
       GlobalVariable.setDatabase(s);
      }
      catch(Exception e)
      {
       error = true;
      }
      if(error)
       response.sendRedirect("switchdatabaseunsuccess.jsp");
      else
       response.sendRedirect("switchdatabasesuccess.jsp");
     }
    }
     

    Hibernate Example - 2


    hibernate.cfg.xml

    Employee.java
    package com.hibernate.test2
    import javax.persistence.Entity;
    import javax.persistence.Id;
    
    @Entity   
    public class Employee
    {
     private int empid;
     private Strign empname; 
     @Id
     public int getEmpid()
     {
    return empid;
    }
    
    public void setEmpid(int empid)
    {
    this.empid=empid;
    }
    
    public int getEmpName()
    {
    return empname;
    }
    
    public void setEmpName(int empname)
    {
    this.empname=empname;
    }
    }
    


    TestEmployee.java
    package com.hibernate.test2
    public class TestEmployee{
    public static void main(String[] args) {
    
    AnnotationConfiguration config = new AnnotationConfiguration();
    config.addAnnotatedClass(Employee.class);
    config.configure();
    
    new SchemaExport(config).create(true,true);
     
    SessionFactory factory = config.buildSessionFactory();
    Session session =  factory.getCurrentSession();
    
    
     session.beginTransaction();
    
     // Insert
     Employee a = new Employee();
     a.setEmpId(100);
     a.serEmpName("ravi");
     session.save(a);
     session.getTransaction().commit();
    
     }
    }
    

    7. Result

  • Create Query


  • Insert Query


  • Save Data in Database

    8. Advantages

    1) Database independent application
    Hibernate is database independent and you can use any database of your choice.

    2) Hibernate is better then plain JDBC:
    You can use Hibernate which generates the SQL on the fly and then automatically executes the necessary SQL statements. This saves a lot of development and debugging time of the developer.

    3) Mapping of Domain object to relational database:
    Hibernate maps your domain object with the relational database. Now you can concentrate on your business logic rather than managing the data in database.

    4) Layered architecture:
    Hibernate is layers architecture and you can use the components as per your application need.

    5) JPA Provider
    Hibernate can work as JPA provider in JPA based applications.

    6) Standard ORM:
    Hibernate is standard ORM solutions and it also supports JPA.

    7) Caching Framework:
    There are many caching framework that works with Hibernate. You can use any one in your application to improve the performance of your application.

    9. Disadvantage

    1) Lots of API to learn:
    A lot of effort is required to learn Hibernate. So, not very easy to learn hibernate easily.

    2) Debugging:
    Sometimes debugging and performance tuning becomes difficult.

    3) Slower than JDBC:
    Hibernate is slower than pure JDBC as it is generating lots of SQL statements in runtime

    4) Not suitable for Batch processing:
    It advisable to use pure JDBC for batch processing.


    14. Hibernate 4.0

    JIRA filter link which lists all improvements and new features in Hibernate Core 4.0.0, you can get all details from this link :)
    Some highlights:
    move to gradle for builds
    Improved metamodel (not in 4.0.0.Final yet, we planned this, but due to the tasks are more than we expected, and it would take too long to get 4.0 out, so we decided to move this out of 4.0.0.Final but will be upcoming release soon see this for more details, and this is a design document)
    Support for multi-tenant databases (see this for more details)
    Migration to i18n logging framework (using jboss logging)

    15. Hibernate Vs. Others

  • Other popular ORMs are
    – iBatis
    – JPA
    – TopLink
  • iBatis
    – Needs SQL Statements to be coded in its Mapping files
    – Good when developer needs control over the SQL
  • TopLink
    – Very similar and quite powerful but costs



    Done :)
  • Post a Comment

    8 Comments

    1. gret docs..............

      ReplyDelete
    2. Howdy! This is kind of off topic but I need some advice from an established blog.
      Is it difficult to set up your own blog? I'm not very techincal but
      I can figure things out pretty fast. I'm thinking about setting up my own but I'm not
      sure where to start. Do you have any points or suggestions?
      Many thanks

      my page :: iddaa siteleri

      ReplyDelete
    3. Greetings! Very helpful advice in this particular article!

      It's the little changes that will make the most significant changes.

      Thanks for sharing!

      Look at my page; Christian Louboutin Discount

      ReplyDelete
    4. You've made some good points there. I checked on the web for more info about
      the issue and found most people will go along with your
      views on this site.

      My page - Christian Louboutin Discount; crashed-gaming.xaa.pl,

      ReplyDelete
    5. Good day! I could have sworn I've visited this website before but after going through many of the articles I realized it's
      new to me. Anyhow, I'm certainly happy I stumbled upon it and
      I'll be bookmarking it and checking back frequently!


      my webpage: Christian Louboutin Outlet

      ReplyDelete
    6. I'll immediately grasp your rss as I can't in finding your email subscription hyperlink or e-newsletter service.

      Do you've any? Please allow me know so that I may subscribe.

      Thanks.

      Also visit my homepage; Cheap GHD

      ReplyDelete
    7. Thanks for the marvelous posting! I quite enjoyed reading it, you could be a great author.
      I will make certain to bookmark your blog and may come back later on. I want to encourage
      that you continue your great posts, have a nice
      day!

      Feel free to surf to my page; dragon city hack tool

      ReplyDelete
    8. Whoa! This blog looks exactly like my old one! It's on a
      entirely different subject but it has pretty much the same layout and design. Great choice of colors!


      Look into my weblog ... Christian Louboutin Shoes

      ReplyDelete