Ian P. Christian's Personal Blog Random witterings from pookey

1Aug/0810

Hibernate with MySQL – a beginners guide – part 3

In part 1 and part 2 I showed how to get up and running with hibernate. This part continues from where we left off.

I have packaged up all the files form part 2, including all required jars, and the build script. The file is 4.5meg, and is downloadable here: hibernate.tar.gz. Having got the the unit testing setup and running in part 2, I'll not cover creating more tests here. When developing your own code though, you should of course be writing tests as you go along!

In this part, I'll show you how to load this object from the database, edit it, and save it back again. Relationships (for example, linking comments to the blog post) are quite complicated, so I'll leave that to part 4. This part is almost entirely shown though example code - however I think the code speaks for itself.

The first thing I'll demonstrate is deleting all records from a table. We'll add this to the application so that everytime it is run, we start with an empty table. Before doing that, I'm going to create a new class which I'll use to host the main() method, as it doesn't really belong in the HibernateUtil package as it was in part 2.

First, build.xml needs modifying so that it knows what class to run when we execute ant run.

    <target name="run" depends="compile">
        <java fork="true" classname="uk.co.pookey.BlogApp" classpathref="libraries">
            <classpath path="${targetdir}"/>
            <arg value="${action}"/>
        </java>
    </target>

Here's several of the features of hibernate shown off in a single class. The inline comments (forgive the lack of javadoc comments, my blog highlight engine didn't like them!) explain what's going on. When fetching data from Hibernate, you can use a Criteria API (as shown in getBlogsBySubject()), HQL (deleteAll()) or even by using SQL.

package uk.co.pookey;                                               
 
import uk.co.pookey.hibernate.HibernateUtil;
import uk.co.pookey.Blog;                   
import org.hibernate.Session;               
import org.hibernate.Transaction;           
import org.hibernate.Criteria;              
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Order;       
import java.util.List;                      
import java.util.Iterator;                  
 
public class BlogApp {
 
  // Deletes all Blog data
  // This function shows the use of HQL - Hibernate Query Lanaguage
  public void deleteAll() {                                        
    Session session = HibernateUtil.getSession();                  
 
    session.beginTransaction();
 
    session.createQuery("delete from Blog").executeUpdate();
 
    session.getTransaction().commit();                      
  }                                                         
 
  // Creates a Blog with specificed subject and name
  public Blog createBlog(String subject, String body) {
 
    Blog b = new Blog();
    b.setSubject(subject);
    b.setBody(body);      
 
    Session session = HibernateUtil.getSession();
 
    session.beginTransaction();
 
    session.save(b);
 
    session.getTransaction().commit();
 
    return b;
 
  }
 
  // Searches for all Blogs with a subject matching the supplied param.
  // This shows the use of the Criteria API                            
  public List<Blog> getBlogsBySubject(String subject) {                
 
    Session session = HibernateUtil.getSession();
 
    session.beginTransaction();
 
    List<Blog> blogs = session.createCriteria(Blog.class)
      .add( Restrictions.like("subject", "%" + subject +  "%") )
      .addOrder(Order.asc("id"))                                
      .list();                                                  
 
    session.getTransaction().commit();
 
    return blogs;
  }              
 
  // Fetches a single Blog by id
  public Blog getBlogById(Long id) {
 
    Session session = HibernateUtil.getSession();
 
    session.beginTransaction();
 
    Blog ret = (Blog) session.get(Blog.class, id);
 
    session.getTransaction().commit();
 
    return ret;
  }
 
  // Updates the subject for a particular Blog
  public void updateSubject(Long id, String subject) {
 
    Session session = HibernateUtil.getSession();
 
    session.beginTransaction();
 
    Blog b = this.getBlogById(id);
 
    b.setSubject(subject);
    session.update(b);
 
    session.getTransaction().commit();
    session.flush();
 
  }
 
  public static void main (String[] args) {
    BlogApp app = new BlogApp();
 
    app.deleteAll();
    System.out.println("All blog posts deleted");
 
    Blog post1 = app.createBlog("Subject #1", "Some content here...");
    System.out.println("Blog post inserted with ID: " + post1.getId());
 
    Blog post2 = app.createBlog("Subject #2", "some more content!");
    System.out.println("Blog post inserted with ID: " + post2.getId());
 
    Blog post3 = app.getBlogById(new Long(1));
    System.out.println("Blog returned has a subject of: " + post3.getSubject());
 
    List<Blog> blogs = app.getBlogsBySubject("Sub");
 
    System.out.println("Looking for posts with 'Sub' within the subject line");
    Iterator<Blog> iterator = blogs.iterator();
    if (iterator.hasNext()) {
      while (iterator.hasNext()) {
        Blog b = iterator.next();
        System.out.println("\tFound: " + b.getId() + ", with subject: " + b.getSubject());
      }
    }
    else {
      System.out.println("nothing found!");
    }
  }
 
}

Below shows the output of running the application now, showing all the SQL statements.

run:
     [java] log4j:WARN No appenders could be found FOR logger (org.hibernate.cfg.Environment).
     [java] log4j:WARN Please initialize the log4j system properly.                           
     [java] Hibernate:                                                                        
     [java]     DELETE                                                                        
     [java]     FROM                                                                          
     [java]         blog                                                                      
     [java] ALL blog posts deleted                                                            
     [java] Hibernate:                                                                        
     [java]     SELECT                                                                        
     [java]         MAX(id)                                                                   
     [java]     FROM                                                                          
     [java]         blog                                                                      
     [java] Hibernate:                                                                        
     [java]     INSERT                                                                        
     [java]     INTO                                                                          
     [java]         blog                                                                      
     [java]         (subject, body, createdAt, id)                                            
     [java]     VALUES                                                                        
     [java]         (?, ?, ?, ?)                                                              
     [java] Blog post inserted WITH ID: 1                                                     
     [java] Hibernate:                                                                        
     [java]     INSERT                                                                        
     [java]     INTO                                                                          
     [java]         blog                                                                      
     [java]         (subject, body, createdAt, id)                                            
     [java]     VALUES                                                                        
     [java]         (?, ?, ?, ?)                                                              
     [java] Blog post inserted WITH ID: 2                                                     
     [java] Hibernate:
     [java]     SELECT
     [java]         blog0_.id AS id0_0_,
     [java]         blog0_.subject AS subject0_0_,
     [java]         blog0_.body AS body0_0_,
     [java]         blog0_.createdAt AS createdAt0_0_
     [java]     FROM
     [java]         blog blog0_
     [java]     WHERE
     [java]         blog0_.id=?
     [java] Blog returned has a subject OF: Subject #1
     [java] Hibernate:
     [java]     SELECT
     [java]         this_.id AS id0_0_,
     [java]         this_.subject AS subject0_0_,
     [java]         this_.body AS body0_0_,
     [java]         this_.createdAt AS createdAt0_0_
     [java]     FROM
     [java]         blog this_
     [java]     WHERE
     [java]         this_.subject LIKE ?
     [java]     ORDER BY
     [java]         this_.id ASC
     [java] Looking FOR posts WITH 'Sub' WITHIN the subject line
     [java]     Found: 1, WITH subject: Subject #1
     [java]     Found: 2, WITH subject: Subject #2
Filed under: geek, java Leave a comment
Comments (10) Trackbacks (0)
  1. Thanks this tutorial works, and easy to understand as i m new to java hibernate it helped my lot.

    Thanks
    VM

  2. Thanks for the tutorial! It’s great. I’m looking forward to reading the fourth part.
    Best regards,
    Danut

  3. Hi Every One, This tutorial is awesome for beginners ,
    really helped me a a lot
    thank you very much for this

  4. In the last part of my hibernate tutorials I showed how to get a simple application inserting data into a database. This part doesn’t expand on that in terms of features, in fact, this tutorial actually does less! However, the last tutorial required

  5. Your tutorials are great and very easy!!!!

    I had problems with this last one but was able to find the problem.

    Error I got:

    compile:
    [javac] Compiling 4 source files to C:\hibernate\bin
    [javac] C:\hibernate\src\uk\co\pookey\BlogApp.java:57: warning: [unchecked]
    unchecked conversion
    [javac] found : java.util.List
    [javac] required: java.util.List
    [javac] .list();
    [javac] ^
    [javac] 1 warning

    run:
    [java] log4j:WARN No appenders could be found for logger (org.hibernate.cfg
    .Environment).
    [java] log4j:WARN Please initialize the log4j system properly.
    [java] Exception in thread “main” java.lang.NoClassDefFoundError: antlr/ANT
    LRException
    [java] at org.hibernate.hql.ast.ASTQueryTranslatorFactory.createQueryTr

    So what I did is added antlr-2.7.6.jar to the C:\hibernate\lib.

    Thank you for the help!!!!!

  6. Superb,
    Brilliant tutorial for the beginners like me.I got to know the abc of hibernate.
    Great work and here is a BIG THANKS.
    keep making life arround better.keep it up.

  7. Hi all,
    while commiting session.getTransaction().commit(); is being used,which in turn gets a new transaction and commits it rather than commiting the intended transaction on which operations has been performed.

    so I think we need to collect the Transaction in a Transaction type variable and then commit the same so that this transcation will be committed to the database.

  8. Wonderfull, all your tuto are wonderfull… I do all the tuto with eclipse and it is perfect. Just 2 things:
    -update the jar list
    -change in part 1

    into

    Thanks a lot.

  9. I have searched in a lot of web tutorials and this is the best tutorial that I have found.

    Just a little comment, I would be better if you add the sql script. in the tutorial.

    This is the MySQL Script for the people that could be need it.

    mysql > create database hibernate;
    mysql > create table blog (
    > id INT(10),
    > subject VARCHAR(100),
    > body VARCHAR(2000),
    > createAt Date);

    Thanks & Regards


Leave a comment

No trackbacks yet.