2320457 What is Hibernate

Embed Size (px)

Citation preview

  • 8/9/2019 2320457 What is Hibernate

    1/10

    What is Hibernate?

    Hibernate 3.0, the latest Open Source persistence technology at the heart of J2EE EJB 3.0is available for download from Hibernet.org.The Hibernate 3.0 core is 68,549 lines of

    Java code together with 27,948 lines of unit tests, all freely available under the LGPL,and has been in development for well over a year. Hibernate maps the Java classes to the

    database tables. It also provides the data query and retrieval facilities that significantlyreduce the development time. Hibernate is not the best solutions for data centric

    applications that only uses the stored-procedures to implement the business logic in

    database. It is most useful with object-oriented domain modes and business logic in theJava-based middle-tier. Hibernate allows transparent persistence that enables the

    applications to switch any database. Hibernate can be used in Java Swing applications,

    Java Servlet-based applications, or J2EE applications using EJB session beans.

    Features of Hibernate

    Hibernate 3.0 provides three full-featured query facilities: Hibernate Query

    Language, the newly enhanced Hibernate Criteria Query API, and enhanced

    support for queries expressed in the native SQL dialect of the database.

    Filters for working with temporal (historical), regional or permissioned data.

    Enhanced Criteria query API: with full support for projection/aggregation and

    subselects.

    Runtime performance monitoring: via JMX or local Java API, including a second-

    level cache browser.

    Eclipse support, including a suite of Eclipse plug-ins for working with Hibernate

    3.0, including mapping editor, interactive query prototyping, schema reverseengineering tool.

    Hibernate is Free under LGPL: Hibernate can be used to develop/package and

    distribute the applications for free.

    Hibernate is Scalable: Hibernate is very performant and due to its dual-layer

    architecture can be used in the clustered environments.

    Less Development Time: Hibernate reduces the development timings as it

    supports inheritance, polymorphism, composition and the Java Collection

    framework.

    Automatic Key Generation: Hibernate supports the automatic generation of

    primary key for your.

    http://www.roseindia.net/hibernate/introduction.shtmlhttp://www.roseindia.net/hibernate/introduction.shtmlhttp://www.roseindia.net/hibernate/introduction.shtmlhttp://www.roseindia.net/hibernate/introduction.shtml
  • 8/9/2019 2320457 What is Hibernate

    2/10

    JDK 1.5 Enhancements: The new JDK has been released as a preview earlier this

    year and we expect a slow migration to the new 1.5 platform throughout 2004.

    While Hibernate3 still runs perfectly with JDK 1.2, Hibernate3 will make use ofsome new JDK features. JSR 175 annotations, for example, are a perfect fit for

    Hibernate metadata and we will embrace them aggressively. We will also support

    Java generics, which basically boils down to allowing type safe collections.

    EJB3-style persistence operations: EJB3 defines the create () and merge ()

    operations, which are slightly different to Hibernate's saveOrUpdate ()and

    saveOrUpdateCopy ()operations. Hibernate3 will support all four operations as

    methods of the Session interface.

    Hibernate XML binding enables data tobe represented as XML and POJOs

    interchangeably.

    The EJB3 draft specification support for POJO persistence and annotations.

    As per http://www.hibernate.org, Hibernate is a powerful, ultra-high performanceobject/relational persistence and query service for Java. Hibernate gives you the option to

    code and work with Java and use Hibernate's capabilities to interact with the database.No need to write SQL in your Java code. You work with Java objects and Hibernate doesthe rest.

    In this "Quick Hibernate" series of articles, Satish Talim gets you started with Hibernate.Satish's hands-on approach should have you developing with Hibernate in no time.

    Also check out Satish's interview: Java and J2EE Today

    Quick Hibernate

    We need a means of taking information from a SQL database and turn it into Java objects,

    and vice-versa. The general problem is known as Object/Relational Mapping. Hibernate

    is a lightweight O/R mapping service for Java and gives you the means for persisting

    your Java objects to and from an underlying database. Rather than you writing the SQLand converting queries to and from first class objects, Hibernate can take care of all this

    for you. You only concern yourself with the objects, Hibernate worries about the SQL andmaking sure things end up in the right tables.

    There are many books and articles available on Hibernate and what I want to do here is

    quickly get you started with Hibernate. I want to take this opportunity to thankGlenSmith for showing me the quick way to get started with Hibernate and this blog is based

    http://www.roseindia.net/hibernate/introduction.shtmlhttp://www.hibernate.org/http://www.hibernate.org/http://www.indicthreads.com/blogs/quick_hibernate.htmlhttp://www.indicthreads.com/blogs/quick_hibernate.htmlhttp://indicthreads.com/interviews/java_j2ee_today.htmlhttp://www.indicthreads.com/blogs/quick_hibernate.htmlhttp://www.roseindia.net/hibernate/introduction.shtmlhttp://www.hibernate.org/http://www.indicthreads.com/blogs/quick_hibernate.htmlhttp://indicthreads.com/interviews/java_j2ee_today.htmlhttp://www.indicthreads.com/blogs/quick_hibernate.html
  • 8/9/2019 2320457 What is Hibernate

    3/10

    on that and dedicated to him.

    Quick Installation and Setup

    Install J2SDK 1.4.2

    InstallAnt Go to http://www.hibernate.org/ and download Hibernate

    InstallHibernate by unzipping the file hibernate-2.1.6.zip to drive say F:

    Setup a Project Hierarchy by doing the following Create folder F:hlogin and then

    create sub-folders F:hloginsrc and F:hloginlib

    Copy all the contents of F:hibernate-2.1lib to F:hloginlib

    Copy hibernate2.jar to F:hloginlib

    The example classes we are going to create are all going to reside in the folder

    F:hloginsrccomtalimdemo. Create these sub-folders.

    Quick Compile

    ?

    To quickly compile your Java code:

    ?

    At the folderF:hlogin type ant

    To run your Hibernate programs

    At the folderF:hlogin type ant run

    >> Resource: Build.xml

    The Development Process

    ?

    There are several ways to approach Hibernate development. Here's the one that isprobably the most straightforward to understand:

    Create your SQL table to hold your persistent objects

    Create a Java bean that will represent that object in code Create a mapping file that Hibernate knows which bean properties map to which

    SQL fields

    Create a properties file so Hibernate knows your JDBC settings to get to the

    database

    Start using the Hibernate API

    http://indicthreads.com/content/blogs/hibernate/build.xmlhttp://www.indicthreads.com/content/view/55/1/1/1/http://www.indicthreads.com/content/view/55/1/1/1/http://www.indicthreads.com/content/view/55/1/1/1/http://indicthreads.com/content/blogs/hibernate/build.xmlhttp://www.indicthreads.com/content/view/55/1/1/1/http://www.indicthreads.com/content/view/55/1/1/1/
  • 8/9/2019 2320457 What is Hibernate

    4/10

    As you get more proficient, there are tools to help auto-generate either Beans from SQL

    or SQL from Beans (and even plug-ins to make the mapping file for you), but let's do it

    the long way first, so you don't get distracted.

    Step 1: Create the table

    ?

    The example we're working through is a very simple one. Lets say you need a users table

    (in say database jboss).

    CREATE TABLE myusers (

    LogonID varchar(20) NOT NULL default '0',

    Name varchar(40) default NULL,

    Password varchar(20) default NULL,

    EmailAddress varchar(40) default NULL,

    LastLogon datetime default NULL,

    PRIMARY KEY (LogonID)

    );

    We are using mySql, but you can use any database that you have a JDBC driverfor.We've got a User table with a Logon ID, Full Name, Password, Email and date of lastlogon. Next step is to write a Java bean to handle a given User

    Step 2: Write the Bean

    Hibernate works via reflection on get/set methods of the objects, so we'll need to createthe objects (as beans) we want to persist.

    package com.talim.demo;import java.util.Date;

    import java.io.Serializable;

    public class MyUsers implements Serializable{

    private String userID;

    private String userName;private String password;

    http://www.indicthreads.com/content/view/55/1/1/1/http://www.indicthreads.com/content/view/55/1/1/1/
  • 8/9/2019 2320457 What is Hibernate

    5/10

    private String emailAddress;

    private Date lastLogon;

    public MyUsers(){

    }

    public String getID()

    {return userID;

    }

    public void setID(String userID)

    {this.userID = userID;

    }

    public String getUserName()

    {return userName;

    }

    public void setUserName(String userName)

    {this.userName = userName;

    }

    public String getPassword(){return password;

    }

    public void setPassword(String password)

    {this.password = password;

    }

    public String getEmailAddress()

    {return emailAddress;

    }

    public void setEmailAddress(String emailAddress){

    this.emailAddress = emailAddress;

    }

  • 8/9/2019 2320457 What is Hibernate

    6/10

    public Date getLastLogon()

    {

    return lastLogon;}

    public void setLastLogon(Date lastLogon){

    this.lastLogon = lastLogon;}

    }

    Step 3: Writing the Mapping File

    So we've now got our SQL table, and the Java object that's going to map to it. We stillneed a way to tell Hibernate how to map from one to the other. This is accomplished via a

    mapping file.Hibernate uses an XMl document to track the mapping between Java

    classes andrelational database

    tables.

    ?

    The cleanest (most maintainable) way is to write one mapping file per object, and if you

    name it YourObject.hbm.xml and put it in the same directory

    (F:hloginsrccomtalimdemo)as your real object, Hibernate will make things even easierfor you. Here's an example of what MyUsers.hbm.xml might look like:

    Resource: MyUsers.hbm.xml

    Let's have a look at some lines of interest in our file. The first tag of interest is the class tag. Here we map

    from the class name to the users table in ourdatabase. Let's skip the ID tag for a moment and talk aboutthe property tags. A cursory scan will show this is where the work is being done. The name attribute is the

    property on ourJava bean, and the column is the name of the field in our database. The type attribute isoptional (Hibernate will use reflection for a best-guess if you leave it out) - but I've put it in here for

    completeness.

    ?

    Ok. Let's return to that ID tag. You may have guessed that this tag has something to do

    with mapping to the primary key of the table. You'd be right. The form of the ID tag is

    very similar to the property tags we just looked at. We map from the bean property(name) to the target database field (column).

    ?

    ?

    http://www.indicthreads.com/content/view/55/1/1/2/http://www.indicthreads.com/content/view/55/1/1/2/http://indicthreads.com/content/blogs/hibernate/MyUsers.hbm.xmlhttp://indicthreads.com/content/blogs/hibernate/MyUsers.hbm.xmlhttp://indicthreads.com/content/blogs/hibernate/MyUsers.hbm.xmlhttp://www.indicthreads.com/content/view/55/1/1/2/http://www.indicthreads.com/content/view/55/1/1/2/http://www.indicthreads.com/content/view/55/1/1/2/http://www.indicthreads.com/content/view/55/1/1/2/http://www.indicthreads.com/content/view/55/1/1/2/http://www.indicthreads.com/content/view/55/1/1/2/http://indicthreads.com/content/blogs/hibernate/MyUsers.hbm.xmlhttp://www.indicthreads.com/content/view/55/1/1/2/http://www.indicthreads.com/content/view/55/1/1/2/
  • 8/9/2019 2320457 What is Hibernate

    7/10

    The embedded generator tag tells Hibernate how it should produce the primary key (it's

    quite happy to generate one for you, of whatever type you prefer, but you'll need to tell it

    how). In our case, we set it to assigned, meaning that our bean is going to generate itsown keys (the User object will always need to have a UserID after all).

    ?

    Step 4: Creating a Properties File for Your Database

    We still haven't told Hibernate where to find our database. The most straightforward way

    is to feed Hibernate a properties object, with settings for the connection strings,passwords, etc. If you name this file hibernate.properties, copy it to folder

    F:hloginsrc and put it in your classpath, Hibernate will pick it up automatically. Here's

    what it looks like:

    ?

    hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect

    hibernate.connection.driver_class=com.mysql.jdbc.Driver

    hibernate.connection.url=jdbc:mysql://127.0.0.1:3306/jboss

    hibernate.connection.username=

    hibernate.connection.password=

    The example above uses a mysqldriver, connects to the jboss database on 127.0.0.1, anduses the supplied username and password. There are a bunch of other properties you can

    set to "tune" how Hibernate accesses your database of choice. Once again, checkout the

    document for detailed information.

    An alternative approach is to specify a full configuration in a file namedhibernate.cfg.xml. This file can be used as a replacement for the hibernate.properties file

    or, if both are present, override properties. The XML configuration file is by default

    expected to be in the root of your CLASSPATH.

    Step 5: Start using the Hibernate API

    If all has gone well so far, you'll have the following:

    ?

    A SQL User table in your database

    MyUsers.java - your Java bean object to persist

    http://www.indicthreads.com/content/view/55/1/1/2/http://www.indicthreads.com/content/view/55/1/1/2/http://www.indicthreads.com/content/view/55/1/1/2/
  • 8/9/2019 2320457 What is Hibernate

    8/10

    MyUsers.hbm.xml - your Hibernate mapping file

    hibernate.properties - your properties file with JDBC connection info

    Making use of Hibernate in your source is pretty straightforward.

    Create a Configuration object

    Tell the Configuration about the type of objects you want to map

    Create a Session to your database of choice

    Load, Save and Query your objects

    flush() your Session back to the database

    Steps 1 and 2

    ?

    The Configuration object is based on the properties file, we have put in the standard place

    ?

    ?

    Configuration config = new Configuration();

    ?

    Config.addClass(MyUsers.class);

    ?

    This assumes you've got a MyUsers.hbm.xml file in the same directory as your user class.

    If you decided to call your file something else, use

    ds.storeFile("MyMappingFile.hbm.xml").

    ?

    Step 3

    The Session object represents a connection to your backenddatabase. You can feed

    Hibernate a JDBC session that you've created by hand, but I'm lazy, so I'm just going to

    feed Hibernate the properties file with my settings, and let it do the work for me.

    // Then build a session to the database

    SessionFactory sf = config.buildSessionFactory(); // or supply a Properties arg

    Session session = sf.openSession();

    http://www.indicthreads.com/content/view/55/1/1/3/http://www.indicthreads.com/content/view/55/1/1/3/http://www.indicthreads.com/content/view/55/1/1/3/
  • 8/9/2019 2320457 What is Hibernate

    9/10

    I've called my properties file hibernate.properties and put it in my classpath, but if you've

    called yours something different (or you want to create the Properties in code), then you'll

    need to feed your own Properties object to buildSessionFactory().

    Step 4

    Now you just use your objects in a Java-native way. Would you like to store a new User

    in the database? Try something like this:

    // Create new User and store them the database

    MyUsers newUser = new MyUsers();newUser.setID("satish_talim");

    newUser.setUserName("Satish Talim");

    newUser.setPassword("informex");newUser.setEmailAddress([email protected] email address is being protected

    from spam bots, you need Javascript enabled to view it );

    newUser.setLastLogon(new Date());// And the Hibernate call which stores it

    session.save(newUser);

    As you can see, the great thing about Hibernate is the low overhead. For the most part you just worry about

    your business objects, and make a single call to Hibernate when you're done.

    Step 5

    Every so often your Hibernate Session object will flush itself to the database to make the database is in

    sync with your memory copies of objects. You'll want to free up the JDBC connection that Hibernate's

    using, so you'll typically shut down with:

    // close our session and release resources

    session.flush();

    session.close();

    // NB: some non-MySQL (Sybase, etc) database users also need to...

    // session.connection().commit();

    (Depending on your JDBC driver, you'll need to commit the underlying connection too.You don't need this if you're using mySQL, but on other transactional databases (like

    Sybase), you need an extra statement after the close calling

    session.connection().commit()).

    Example

    Heres the code for inserting a record in our table MyUsers

    mailto:[email protected]:[email protected]://www.indicthreads.com/content/view/55/1/1/3/http://www.indicthreads.com/content/view/55/1/1/3/http://www.indicthreads.com/content/view/55/1/1/3/mailto:[email protected]://www.indicthreads.com/content/view/55/1/1/3/http://www.indicthreads.com/content/view/55/1/1/3/
  • 8/9/2019 2320457 What is Hibernate

    10/10

    package com.talim.demo;

    import net.sf.hibernate.*;import net.sf.hibernate.cfg.Configuration;

    import com.talim.demo.MyUsers;import java.util.Date;

    public class MyUsersTest{public static void main(String[] args)throws Exception{

    // Create a configuration based on the properties file we// have put in the standard placeConfiguration config = new Configuration();

    // Tell it about the classes we want mapped, taking advantage

    // of the way we have named their mapping documentsconfig.addClass(MyUsers.class);

    // A SessionFactory is Hibernate's concept of a single datastore

    // Get the sesion factory we can use for persistenceSessionFactory sessionFactory = config.buildSessionFactory();

    // Hibernate's Session, is the persistence manager interface,// we use it to store and retrieve MyUsers to and from the database// Ask for a session using the JDBC information we have configuredSession session = sessionFactory.openSession();

    // Store a new User in the databasetry{MyUsers newUser = new MyUsers();newUser.setID("satish_talim");newUser.setUserName("Satish Talim");newUser.setPassword("informex");

    newUser.setEmailAddress("[email protected] This email address is being protected fromspam bots, you need Javascript enabled to view it ");

    newUser.setLastLogon(new Date());

    // And the Hibernate call which stores itsession.save(newUser);}finally{

    // close our session and release resourcessession.flush();session.close();}

    // Clean up after ourselvessessionFactory.close();}}

    http://www.indicthreads.com/content/view/55/1/1/3/http://www.indicthreads.com/content/view/55/1/1/3/mailto:[email protected]://www.indicthreads.com/content/view/55/1/1/3/mailto:[email protected]