Hibernate

Java-Examples

                                                                                                                                                                                                                    Show all | Close all
  • Overview

    • What is framework

      Framework is set of reusable software program that forms the basis for an application. Frameworks helps the programmers to build the application quickly. Earlier it was very hard to develop complex web applications. Now its very easy to develop such application using different kinds of frameworks such as Struts, Struts 2, Hibernate, JSF, Tapestry, JUnit, Log4j, Spring etc. In Java technology there are so many frameworks that helps the programmers to build complex applications easily. You can choose these frameworks for building your applications.

      Software framework

      Framework software in computer system is a layered structure that indicates what kind of program should be built and how they would interrelate to one another. In computer system, a framework is a conceptual structure that sometime includes actual programs, which specify programming interface or offer programming tools for using the frameworks.
    • Java Collection Framework

      We have tried you to make a walk through the Collection Framework. The Collection Framework provides a well-designed set if interface and classes for sorting and manipulating groups of data as a single unit, a collection.
      The Collection Framework provides a standard programming interface to many of the most common abstractions, without burdening the programmer with too many procedures and interfaces.
      The Collection Framework is made up of a set of interfaces for working with the groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific, implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code.

      In the Collections Framework, the interfaces Map and Collection are distinct with no lineage in the hierarchy. The typical application of map is to provide access to values stored by keys.
      When designing software with the Collection Framework, it is useful to remember the following hierarchical relationship of the four basic interfaces of the framework.
      • The Collection interface is a group of objects, with duplicates allowed.
      • Set extends Collection but forbids duplicates.
      • List extends Collection also, allows duplicates and introduces positional indexing.
      • Map extends neither Set nor Collection
    • Types of Framework

      Struts Struts Frame work is the implementation of Model-View-Controller (MVC) design pattern for the JSP. Struts is maintained as a part of Apache Jakarta project and is open

      Open Source Web Frameworks in Java

      1. Struts
        Struts Frame work is the implementation of Model-View-Controller (MVC) design pattern for the JSP. Struts is maintained as a part of Apache Jakarta project and is open source. Struts Framework is suited for the application of any size. Latest version of struts can be downloaded from http://jakarta.apache.org/.
         
      2. Turbine
        Turbine is a servlet based framework that allows experienced Java developers to quickly build web applications. Turbine allows you to use personalize the web sites and to use user logins to restrict access to parts of your application.
         
      3. Expresso Framework
        A powerful, open standards-based, enterprise-strength J2EE architectural framework providing a library of extensible application development components for quickly building web-based applications.
         
      4. Tapestry
        Tapestry is a powerful, open-source, all-Java framework for creating leading edge web applications in Java. Tapestry reconceptualizes web application development in terms of objects, methods and properties instead of URLs and query parameters. Tapestry is an alternative to scripting environments such as JavaServer Pages or Velocity. Tapestry goes far further, providing a complete framework for creating extremely dynamic applications with minimal amounts of coding.
         
      5. WebWork
        WebWork is a Java web-application development framework. It is built specifically with developer productivity and code simplicity in mind. WebWork is built on top of XWork, which provides a generic command pattern framework as well as an Inversion of Control container. In addition to these features, WebWork provides robust support for building reusable UI templates, such as form controls, UI themes, internationalization, dynamic form parameter mapping to JavaBeans, robust client and server side validation, and much more.
         
      6. Apache Cocoon
        Apache Cocoon is a web development framework built around the concepts of separation of concerns and component-based web development. Cocoon implements these concepts around the notion of 'component pipelines', each component on the pipeline specializing on a particular operation. This makes it possible to use a Lego(tm)-like approach in building web solutions, hooking together components into pipelines without any required programming. Cocoon is "web glue for your web application development needs". It is a glue that keeps concerns separate and allows parallel evolution of all aspects of a web application, improving development pace and reducing the chance of conflicts.
         
      7. Spring
        Spring is a layered Java/J2EE application framework, based on code published in Expert One-on-One J2EE Design and Development.
         
      8. Maverik
        Maverick is a Model-View-Controller (aka "Model 2") framework for web publishing using Java and J2EE. It is a minimalist framework which focuses solely on MVC logic, allowing you to generate presentation using a variety of templating and transformation technologies. In principle it combines the best features of Struts, WebWork, and Cocoon2.

          
      9. Anvil
        Anvil is a Java based server environment and object oriented programming language with templating support, being especially well-suited to for web applications.
          
      10. Jaffa
        JAFFA is aimed at Software development projects that want to focus their energy on building Business Functionality, without spending time on developing the underlying architecture. The JAFFA Project intends to provide a real world application framework, and then build a community of developers around that, who all want an open standards based framework that they can invest in, for building their specific applications on.
          
      11. Japple
        Japple is a rapid application development environment for building web applications and services. Built on the JavaTM2 Platform and open-standards, Japple allows you to develop and deploy web applications faster, easier and more efficiently than traditional methods.
         
      12. JPublish
        JPublish is a powerful web publishing system designed to ensure a clean separation of developer roles. JPublish includes support for multiple templating engines, including Jakarta Apache's Velocity, FreeMarker and WebMacro. JPublish supports numerous scripting languages including Python, BeanShell, and JavaScript. JPublish is modular and provides for easy extensibility.
         
      13. Jucas
        Jucas is a web-framework which brings together the pull MVC concept with component orientated design GUI programming.

        Struts (like other Model II frameworks) have brought the separation between View and Model and Controler to the web programming. On the other hand recent frameworks like Java Server Faces (JSF) or ASP.NET try to provide the advantages of object (component) orientated GUI-Design known from 'fat-client' apis like Swing or Visual Basic (stateful objects, event-mechanismus).

        Jucas combines both approaches. Stateful components (JavaBeans) are used to represent the model and the controller and templates use this components to render the view.
         
      14. MyFaces
        JavaServer(tm) Faces is a new and upcoming web application framework that accomplishes the MVC paradigm. It is comparable to the well-known Struts Framework but has features and concepts that are beyond those of Struts.
        Look at Sun's JavaServer(tm) Page to learn more about the Java Specification Request 127 and to download the specification. They also provide a useful Tutorial there.
         
      15. WebOnSwing
        WebOnSwing is a revolutionary multiple environment application framework that allows you to create web applications in the same way you develope a desktop one. You dont need to use JSP files, special tags, XML files, requests, posts, etc. Everything is Java and pure HTML files that comes directly from the graphic designer.
         
      16. Chrysalis
        Chrysalis is a Java web development framework. It has a different focus from most Model-View-Controller (MVC) web frameworks. Chrysalis controllers resemble normal Java classes with multiple methods. Client request URLs are mapped to each controller method. The typical MVC framework is founded on one basic insight: that Java servlets can be treated as an event handler for the submit button of HTML forms. This makes servlets analogous to the controller in the MVC pattern, equivalent to the Listener classes used in Java GUIs. From this insight, the rest of the pattern follows easily (see Struts for the most popular implementation of this approach).
          
      17. VRaptor
        VRaptor is a Model-View-Controller web application framework that tries to implement the best features from the following state of art MVC frameworks: WebWork 2, Spring Framework and Struts. It is highly focused on the Inversion of Control principles, using the Constructor Injection philosophy brought by the PicoContainer.
         
      18. Swinglets
        Program your JSP & Servlets like you program your Swing components. Swinglets is a server side component library that uses an identical design to Swing. Swinglets has look and feels for HTML, JavaScript and WML. The Components, Models, Renderers, and LookAndFeels are very similar. It has Swing event handling too. In fact Swinglets actually uses the Swing models (e.g. TableModel). This means you can take your existing models and start working with Servlets straight away. It's just about as close to a standard as you can get without it actually coming from Sun themselves.
         
      19. Millstone
        Millstone is a user interface library for development of networked Java applications. It provides a terminal independent component model that can be adapted to different terminal types and user interface themes. The development model of Millstone is closely related to traditional client side UI development: it has a continuous application lifecycle and an extensive event model. The Millstone library also provides an interface for directly connecting UI components to business logic and data storage.
         
      20. Wicket
        Wicket is a Java web application framework that takes simplicity, separation of concerns and ease of development to a whole new level. Wicket pages can be mocked up, previewed and later revised using standard WYSIWYG HTML design tools. Dynamic content processing and form handling is all handled in Java code using a Swing-like component model backed by POJO data beans that can easily be persisted with Hibernate.
          
  • Hibernate framework

    Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions. Hibernate is free software that is distributed under the GNU Lesser General Public License. Hibernate's primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. It also generates the SQL calls and attempts to relieve the developer from manual result set handling and object conversion and keep the application portable to all supported SQL databases with little performance overhead
  • History

    Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features. Early in 2003, the Hibernate development team began Hibernate2 releases which offered many significant improvements over the first release. JBoss, Inc. (now part of Red Hat) later hired the lead Hibernate developers and worked with them in supporting Hibernate. In 2010, Hibernate version 3.x was released with the features like: a new Interceptor/Callback architecture, user defined filters, and JDK 5.0 Annotations (Java's metadata feature). As of 2010 Hibernate 3 (version 3.5.0 and up) was a certified implementation of the Java Persistence API 2.0 specification via a wrapper for the Core module which provides conformity with the JSR 317 standard.[2] In Dec 2011, Hibernate Core 4.0.0 Final was released. This includes new features like: Initial multi-tenancy support, Introduction of ServiceRegistry (which is a major change in how Hibernate builds and manages "services"), Clean up of Session opening from SessionFactory, Improved integration via org.hibernate.integrator.spi.Integrator and auto discovery, Improved logging with i18n support and message codes, Initial work on more clear split between API, SPI and implementation classes, Clean up of deprecated methods, classes, etc.[3] In 2012, Hibernate 5 started development. It will contain JPA 2.1 support.
  • Mapping & persistance

    MAPPING

    Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java Annotations. When using an XML file, Hibernate can generate skeletal source code for the persistence classes. This is unnecessary when annotations are used. Hibernate can use the XML file or the annotations to maintain the database schema. Facilities to arrange one-to-many and many-to-many relationships between classes are provided. In addition to managing associations between objects, Hibernate can also manage reflexive associations where an object has a one-to-many relationship with other instances of its own type. Hibernate supports the mapping of custom value types. This makes the following scenarios possible: Overriding the default SQL type that Hibernate chooses when mapping a column to a property. Mapping Java Enum to columns as if they were regular properties. Mapping a single property to multiple columns.

    PERSISTANCE

    Hibernate provides transparent persistence for Plain Old Java Objects (POJOs). The only strict requirement for a persistent class is a no-argument constructor, not necessarily public. Proper behavior in some applications also requires special attention to the equals() and hashCode() methods.[1] Collections of data objects are typically stored in Java collection objects such as Set and List. Java generics, introduced in Java 5, are supported. Hibernate can be configured to lazy load associated collections. Lazy loading is the default as of Hibernate 3. Related objects can be configured to cascade operations from one to the other. For example, a parent such as an Album object can be configured to cascade its save and/or delete operation to its child Track objects. This can reduce development time and ensure referential integrity. A dirty checking feature avoids unnecessary database write actions by performing SQL updates only on the modified fields of persistent objects.
  • Software Components

    The Hibernate software includes the following components:
      Hibernate ORM (was known as Hibernate Core before release 4.1[5]) - the base software for an object-relational mapping solution for Java environments.
      Hibernate Annotations (merged into Hibernate Core/ORM since version 3.6[7]) - metadata that governs the transformation of data between the object-oriented model and the relational database model according to the JSR 317 Java Persistence API (JPA 2).
      Hibernate EntityManager - together with Hibernate Annotations, a wrapper that implements a JSR 317 Java Persistence API (JPA 2) persistence solution on top of Hibernate Core.
      Hibernate Envers - auditing and versioning of persistent classes.
      Hibernate OGM - Object/Grid Mapper is an extension to store data in a NoSQL store.
      Hibernate Shards - horizontal partitioning for multiple relational databases.
      NOTE: Hibernate Shards is not compatible with the 4.x versions of Hibernate Core... some of the Shards capability was integrated into Core in the 4.0 release.
      Hibernate Search - integrates the full text library functionality from Apache Lucene in the Hibernate and JPA model.
      Hibernate Tools - a set of tools implemented as a suite of Eclipse plugins and Ant tasks included in JBoss Developer Studio.
      Hibernate Validator - the reference implementation of JSR 303 Bean Validation.
      Hibernate Metamodel Generator - an annotation processor that creates JSR 317 Java Persistence API (JPA 2) static metamodel classes using the JSR 269 Pluggable Annotation Processing API.
      NHibernate - an object-relational mapping solution for the .NET Framework.
  • Hibernate Simple Program Using Java Application with Eclipse

    Step by Step tutorial to run your Simple Hibernate Program in Eclipse IDE

    Step - 1 Creating Java Project
    Step - 2 SimpleProgram Hibernate Project structure
    Step - 3 Adding Jar Files
    Step - 4 Creating your SimpleProgram Hibernate program(Controller & Pojo)
    Step - 5 Creating hibernate.cfg.xml
    Step - 6 Creating Student.hbm.xml
    Step - 7 OutPut for Running Console hiberanate application
    Step - 8 OutPut for Running Oracle hibernate application

    . This application we will used to insert the data's in database like sql,oracle,DB2 and etc.
    . Here We will see how to save the data's in oracle database .

    Step - 1 Creating Java Project:

    Start Eclipse and goto File -> New -> Project -> Java Project

    Step - 2 SimpleProgram Hibernate Project structure:

    Project Structure:


    Step - 3 Adding Jar Files:

    JAR Files:


    How To Add The JAR Files:

    Right click on project and choose properties

    Step - 4 Creating your SimpleProgram Hibernate program(Controller & Pojo):

    AddStudent.java:

    . Here we will use sessionFactory for create connetion Oracle database.
    sessionFactory = new Configuration().configure(“com\\xml\\hibernate.cfg.xml”).buildSessionFactory();
    . Then we will create objects for pojo classes and then save the database using session.
    Student stu=new Student(); s.save(stu);
    . Then we will use Transaction statement for begin and commit the database.
    Transaction tx= s.beginTransaction(); tx.commit();
    package com.candidjava;
    
    //package code;
    import java.sql.*;
    import java.io.*;
    import org.hibernate.*;
    import org.hibernate.cfg.*;
    
    public class AddStudent {
     private static SessionFactory sessionFactory;
    
     public static void main(String args[]) throws Exception {
    
      DataInputStream d = new DataInputStream(System.in);
      System.out.println("ENTER YOUR NAME");
      String name = d.readLine();
      System.out.println("ENTER YOUR DEGREE");
      String degree = d.readLine();
      System.out.println("ENTER YOUR PHONE");
      String phone = d.readLine();
      System.out.println("Name: " + name);
      System.out.println("Degree: " + degree);
      System.out.println("Phone: " + phone);
      if ((name.equals("") || degree.equals("") || phone.equals(""))) {
       System.out.println("All informations are Required");
      } else {
       try {
        // begin try
        sessionFactory = new Configuration().configure(
          "com\\xml\\hibernate.cfg.xml").buildSessionFactory();
       } catch (Exception e) {
        System.out.println(e.getMessage());
        System.err.println("Initial SessionFactory creation failed."
          + e);
       }
       Session s = sessionFactory.openSession();
       Transaction tx = s.beginTransaction();
       Student stu = new Student();
       stu.setName(name);
       stu.setDegree(degree);
       stu.setPhone(phone);
       s.save(stu);
       tx.commit();
       System.out.println("Added to Database");
       if (s != null)
        s.close();
      }
     }
    }
    

    Student.java:

    . It is a Pojo class. This class Must be a Serializable. Then here we will use get and set method.
    o private long id;
    o public long getId() {return id;}
    o public void setId(long String) {id = String;}
    package com.candidjava;
    
    //package code;
    import java.io.*;
    
    public class Student implements Serializable {
     private long id;
     private String name;
     private String degree;
     private String phone;
    
     public long getId() {
      return id;
     }
    
     public String getName() {
      return name;
     }
    
     public String getDegree() {
      return degree;
     }
    
     public String getPhone() {
      return phone;
     }
    
     public void setId(long string) {
      id = string;
     }
    
     public void setName(String string) {
      name = string;
     }
    
     public void setDegree(String string) {
      degree = string;
     }
    
     public void setPhone(String string) {
      phone = string;
     }
    
     public String toString() {
      return name;
     }
    }
    

    Step - 5 Creating hibernate.cfg.xml:

    hibernate.cfg.xml:

    <property name=”connection.driver_class”> oracle.jdbc.OracleDriver</property>
    Here we will use this property for load the driver in oracle database
    <property name=”connection.url”> jdbc:oracle:thin:@localhost:1521:XE</property>
    Then this property will use for open connetion inoracle database.
    <property name=”connection.username”> system</property>
    This property will use for username in oracle database.
    <property name=”connection.password”> system</property>
    This property will use for password in oracle database
    <property name=”dialect”> org.hibernate.dialect.OracleDialect </property>
    Here we will use oracle Dialect for generating query.
    <!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD//EN"
     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
     <session-factory name="studentFactory">
      <property name="connection.driver_class">
       oracle.jdbc.OracleDriver
             </property>
      <property name="connection.url">
       jdbc:oracle:thin:@localhost:1521:XE
      </property>
      <property name="connection.username">
       system
      </property>
      <property name="connection.password">
       system
      </property>
      <property name="connection.pool_size">5</property>
      <!-- SQL dialect -->
      <property name="dialect">
       org.hibernate.dialect.OracleDialect
             </property>
      <!-- Echo all executed SQL to stdout -->
      <property name="show_sql">true</property>
      <property name="hbm2ddl.auto">create</property>
      <mapping resource="\com\\xml\\Student.hbm.xml" />
     </session-factory>
    </hibernate-configuration>
    

    Step - 6 Creating Student.hbm.xml:

    Student.hbm.xml:

    <class name=”com.candidjava.Student” table=”student” >
    This tag will use for mapping Pojo class name and table name.
    <id name=”id” type=”long” column =”ID”><generator class=”increment”/></id>
    This tag will use for generating primary key id and also increment the id value.
    <property name=”name” column=”name” not-null=”true”/>
    This property will use for mapping the pojo class veriable name(name=”name” ) and table attribute name(column=”name”).
    </class>”/>
    End of the class.
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
     "-//Hibernate/Hibernate Mapping DTD//EN"
     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
     <class name="com.candidjava.Student" table="Studentdemo">
      <id name="id" type="long" column="ID">
       <generator class="increment" />
      </id>
      <property name="name" column="name" not-null="true" />
      <property name="degree" column="degree" />
      <property name="phone" column="phone" />
     </class>
    </hibernate-mapping>
    

    OUTPUT:

    Step - 7 OutPut for Running Console hiberanate application:

    Step - 8 OutPut for Running Oracle hibernate application:a href="images/output19.jpg">



  • Download

    Click here to download Hibernate