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