Raible's Wiki

Raible Designs
Wiki Home
Recent Changes


  - Korean
  - Chinese
  - Italian
  - Japanese

QuickStart Guide
  - Chinese
  - French
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish
  - Japanese

User Guide
  - Korean
  - Chinese

  - Chinese
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish

  - Korean

Latest Downloads

Other Applications

Struts Resume
Security Example
Struts Menu

Set your name in

Referenced by

JSPWiki v2.2.33


Hide Menu


Difference between version 318 and version 226:

At line 1 changed 1 line.
__Part I:__ [Creating new DAOs and Objects in AppFuse|CreateDAO] - A HowTo for creating Java Objects (that represent tables) and creating Java classes to persist those objects in the database.
[this mailing list thread|http://nagoya.apache.org/eyebrowse/ReadMsg?listName=myfaces-user@incubator.apache.org&msgNo=451].
At line 3 changed 2 lines.
!!About this Tutorial
This tutorial will show you how to create a new table in the database, and how to create Java code to access this table.
[What is this SandBox?|WhatIsThisSandBox]
At line 6 changed 1 line.
We will create an object and then some more classes to persist (save/retrieve/delete) that object from the database. In Java speak, we call the object a Plain Old Java Object (a.k.a. a [POJO|http://forum.java.sun.com/thread.jsp?forum=92&thread=425300&tstart=0&trange=15]). This object basically represents a database table. The ''other classes'' will be:
At line 8 changed 2 lines.
* A Data Access Object (a.k.a. a [DAO|http://java.sun.com/blueprints/patterns/DAO.html]), an [Interface|http://java.sun.com/docs/books/tutorial/java/concepts/interface.html] and a Hibernate Implementation
* A [JUnit|http://www.junit.org] class to test our DAO is working
import javax.naming.Context;
import javax.naming.InitialContext;
At line 11 changed 1 line.
AppFuse uses [Hibernate|http://www.hibernate.org] for it's persistence layer. Hibernate is an Object/Relational (O/R) Framework that allows you to relate your Java Objects to database tables. It allows you to very easily perform CRUD (Create, Retrieve, Update, Delete) on your objects.
import junit.framework.TestCase;
At line 13 changed 1 line.
;:''You can also use [iBATIS|http://ibatis.com] as a persistence framework option. To install iBATIS in AppFuse, view the README.txt in {{extras/ibatis}}. If you're using iBATIS over Hibernate, I expect you have your reasons and are familiar with the framework. I also expect that you can figure out how to adapt this tutorial to work with iBATIS. ;-)''
import org.mockejb.MockContainer;
import org.mockejb.SessionBeanDescriptor;
import org.mockejb.jndi.MockContextFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
At line 15 removed 44 lines.
;:%%(color: blue)''I will tell you how I do stuff in the __Real World__ in text like this.''%%
Let's get started on creating a new Object, DAO and Test in AppFuse's architecture.
!Table of Contents
* [1] Create a new Object and add [XDoclet|http://xdoclet.sf.net] tags
* [2] Create a new database table from the object using Ant
* [3] Create a new DaoTest to run JUnit tests on the DAO
* [4] Create a new DAO to perform CRUD on the object
* [5] Configure Spring for the Person object and PersonDao
* [6] Run the DaoTest
!!Create a new Object and add XDoclet tags [#1]
The first thing we need to do is create an object to persist. Let's create a simple "Person" object (in the src/dao/**/model directory) that has an id, a firstName and a lastName (as properties).
package org.appfuse.model;
public class Person extends BaseObject {
private Long id;
private String firstName;
private String lastName;
Generate your getters and setters using your favorite IDE:
In Eclipse:
Right-click -> Source -> Generate Getters and Setters
;:%%(color: blue)''I usually open an existing object (i.e. User.java or Resume.java) and save it as a new file. Then I delete all the methods and properties. This gives me the basic JavaDoc header. I'm sure I could edit Eclipse templates to do this, but since I develop on 3 different machines, this is just easier.''%%
In the code snippet above, we're extending [BaseObject|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/model/BaseObject.java.html] because it has the following useful methods: toString(), equals(), hashCode() - the latter two
are required by Hibernate.
Now that we have this POJO created, we need to add XDoclet tags to generate the Hibernate mapping file. This mapping file is used by Hibernate to map objects → tables and properties (variables) → columns.
First of all, we add a [@hibernate.class|http://xdoclet.sourceforge.net/tags/hibernate-tags.html#@hibernate.class%20(0..1)] tag that tells Hibernate what table this object relates to:
At line 60 changed 1 line.
* @hibernate.class table="person"
* Parent TestCase class for testing EJBs using MockEJB
* @author mraible
At line 62 changed 2 lines.
public class Person extends BaseObject {
public abstract class MockEJBTestCase extends TestCase {
At line 65 changed 1 line.
We also have to add a primary key mapping or XDoclet will puke when generating the mapping file. Note that all @hibernate.* tags should be placed in the __getters'__ Javadocs of your POJOs.
* This method sets up a MockContainer and allows you to deploy an EJB to
* it. Override <code>onSetUp()</code> to add custom set-up behavior.
* @see #onSetUp()
protected final void setUp() throws Exception {
At line 67 changed 1 line.
Context ctx = new InitialContext();
ApplicationContext appCtx =
new ClassPathXmlApplicationContext(getConfigLocations());
ctx.bind("java:comp/env/jdbc/appDS", appCtx.getBean("dataSource"));
MockContainer mc = new MockContainer(ctx);
SessionBeanDescriptor dd = getDeploymentDescriptor();
At line 69 changed 5 lines.
* @return Returns the id.
* @hibernate.id column="id"
* generator-class="increment" unsaved-value="null"
protected String[] getConfigLocations() {
return new String[] { "classpath:/applicationContext.xml" };
At line 75 changed 4 lines.
public Long getId() {
return this.id;
protected void onSetUp() throws Exception {}
At line 80 changed 120 lines.
;:%%(color: blue)''I'm using {{generator-class="increment"}} instead of {{generate-class="native"}} because I [found some issues|AppFuseOnDB2] when using "native" on other databases. If you only plan on using MySQL, I recommend you use the "native" value.''%%
!!Create a new database table from the object using Ant [#2]
At this point, you can actually create the person table by running "ant setup-db". This task creates the Person.hbm.xml file and creates a database table called "person." From the ant console, you can see the table schema the Hibernate creates for your:
[schemaexport] create table person (
[schemaexport] primary key (id)
[schemaexport] )
If you want to look at the Person.hbm.xml file that Hibernate generates for you, look in the build/dao/gen/**/hibernate directory. Here's the contents of Person.hbm.xml (so far):
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
<generator class="increment">
To add non XDoclet property mappings, create a file named
containing the additional properties and place it in your merge dir.
Now we'll add additional [@hibernate.property|http://xdoclet.sourceforge.net/tags/hibernate-tags.html#@hibernate.property%20(0..1)] tags for our other columns (first_name, last_name):
* @return Returns the firstName.
* @hibernate.property column="first_name" length="50"
public String getFirstName() {
return this.firstName;
* @return Returns the lastName.
* @hibernate.property column="last_name" length="50"
public String getLastName() {
return this.lastName;
In this example, the only reason for adding the ''column'' attribute is because the column name is different from our property name. If they're the same, you don't need to specify the ''column'' attribute. See the [@hibernate.property|http://xdoclet.sourceforge.net/tags/hibernate-tags.html#@hibernate.property%20(0..1)] reference for other attributes you can specify for this tag.
Run "ant setup-db" again to get the additional columns added to your table.
{{{[schemaexport] create table person (
[schemaexport] id BIGINT NOT NULL,
[schemaexport] first_name VARCHAR(255),
[schemaexport] last_name VARCHAR(255),
[schemaexport] primary key (id)
[schemaexport] )}}}
If you want to change the size of your columns, specify a length=''size'' attribute in your @hibernate.property tag. If you want to make it a required field (NOT NULL), add not-null="true".
!!Create a new DaoTest to run JUnit tests on your DAO [#3]
Now we'll create a DaoTest to test our DAO works. "Wait a minute," you say, "we haven't created a DAO!" You are correct. However, I've found that [Test-Driven Development|http://www.artima.com/intv/testdriven.html] breeds higher quality software. For years, I thought __write your test before your class__ was hogwash. It just seemed stupid. Then I tried it and I found that it works great. The only reason I do all this test-driven stuff now is because I've found it rapidly speeds up the process of software development.
To start, create a PersonDaoTest.java class in the test/dao/**/persistence directory. This class should extend [BaseDaoTestCase|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/persistence/BaseDaoTestCase.java.html], which already exists in this package. This parent class is used to load [Spring's|http://www.springframework.org] ApplicationContext (since Spring binds the layers together), and for automatically loading a .properties file (ResourceBundle) that has the same name as your *Test.class. In this example, if you put a PersonDaoTest.properties file in the same directory as PersonDaoTest.java, this file's properties will be available via an "rb" variable.
;:%%(color: blue)''I usually copy (open &rarr; save as) an existing test (i.e. UserDaoTest.java) and find/replace [[Uu]ser with [[Pp]erson, or whatever the name of my object is.''%%
package org.appfuse.persistence;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.model.Person;
public class PersonDaoTest extends BaseDaoTestCase {
//~ Instance fields ========================================================
private Person person = null;
private PersonDao dao = null;
//~ Methods ================================================================
protected void setUp() {
log = LogFactory.getLog(PersonDaoTest.class);
dao = (PersonDao) ctx.getBean("personDao");
protected void tearDown() {
dao = null;
public static void main(String[] args) {
protected abstract SessionBeanDescriptor getDeploymentDescriptor();
At line 201 removed 1 line.
At line 203 removed 49 lines.
The code you see above is what we need for a basic JUnit test that initializes and destroys our PersonDao. The "ctx" object is a reference to Spring's ApplicationContext, which is initialized in a static block of the [BaseDaoTestCase's|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/persistence/BaseDaoTestCase.java.html] class.
Now we need to actually test that the CRUD (create, retrieve, update, delete) methods work in our DAO. To do this we created methods that begin with "test" (all lower case). As long as these methods are public, have a void return type and take no arguments, they will be called by our &lt;junit&gt; task in our Ant build.xml file. Here's some simple tests for testing CRUD. An important thing to remember is that each method (also known as a test), should be autonomous. Add the following methods to your PersonDaoTest.java file:
public void testGetPerson() throws Exception {
person = new Person();
person = dao.getPerson(person.getId());
assertEquals(person.getFirstName(), "Matt");
public void testSavePerson() throws Exception {
person = dao.getPerson(new Long(1));
person.setLastName("Last Name Updated");
if (log.isDebugEnabled()) {
log.debug("updated Person: " + person);
assertTrue(person.getLastName().equals("Last Name Updated"));
public void testAddAndRemovePerson() throws Exception {
person = new Person();
assertEquals(person.getFirstName(), "Bill");
if (log.isDebugEnabled()) {
log.debug("removing person...");
At line 254 changed 1 line.
;:%%(color: blue)''In the testGetPerson method, we're creating a person and then calling a get. I usually enter a record in the database that I can always rely on. Since [DBUnit|http://www.dbunit.org] is used to populate our database with test data before our tests are run, you can simply add the new table/record to the metadata/sql/sample-data.xml file:''%%
At line 256 changed 14 lines.
<div style="color: blue !important; margin-left: 50px">
<table name='person'>
At line 271 changed 1 line.
;:%%(color: blue)''This way, you can eliminate the "create new" functionality in the testGetPerson method. If you'd rather add this record directly into the database (via SQL or a GUI), you can rebuild your sample-data.xml file using "ant db-export" and then "cp db-export.xml metadata/sql/sample-data.xml".''%%
[QuickStart Guide_es]
At line 273 changed 7 lines.
In the above example, you can see that we're calling person.set*(value) to populate our object before saving it. This is easy in this example, but it could get quite cumbersome if we're persisting an object with 10 required fields (not-null="true"). This is why I created the ResourceBundle in the BaseDaoTestCase. Simply create a PersonDaoTest.properties file in the same directory as the PersonDaoTest.java file and define your property values inside it:
;:''I tend to just hard-code test values into Java code - but the .properties file is an option.''
Then, rather than calling person.set* to populate your objects, you can use the BaseDaoTestCase.populate(java.lang.Object) method:
At line 281 removed 1 line.
At line 283 changed 132 lines.
person = new Person();
person = (Person) populate(person);
At this point, the PersonDaoTest class won't compile yet because there is no PersonDao.class in our classpath, we need to create it. PersonDAO.java is an interface, and PersonDAOHibernate.java is the Hibernate implementation of that interface. Let's go ahead and create those.
!!Create a new DAO to perform CRUD on the object [#4]
First off, create a PersonDao.java interface in the src/dao/**/persistence directory and specify the basic CRUD methods for any implementation classes. ''I've eliminated the JavaDocs in the class below for display purposes.''
package org.appfuse.persistence;
import org.appfuse.model.Person;
import java.util.List;
public interface PersonDao extends Dao {
public List getPeople(Person person);
public Person getPerson(Long personId);
public void savePerson(Object person);
public void removePerson(Long personId);
Notice in the class above there are no exceptions on the method signatures. This is due to the power of [Spring|http://www.springframework.org] and how it wraps Exceptions with RuntimeExceptions. At this point, you should be able to compile all the source in src/dao and test/dao using "ant compile-dao". However, if you try to run "ant test-dao -Dtestcase=PersonDao", you will get an error: <span style="color: red">No bean named 'personDao' is defined</span>. This is an error message from Spring - indicating that we need to specify a bean named ''personDAO'' in applicationContext-hibernate.xml. Before we do that, we need to create the PersonDao implementation class.
;:''The ant task for running dao tests is called "test-dao". If you pass in a testcase parameter (using -Dtestcase=name), it will look for **/*${testcase}* - allowing us to pass in Person, PersonDao, or PersonDaoTest - all of which will execute the PersonDaoTest class.''
Let's start by creating a PersonDaoHibernate class that implements the methods in PersonDao and uses Hibernate to get/save/delete the Person object. To do this, create a new class in src/dao/**/persistence/hibernate and name it PersonDAOHibernate.java. It should extend [BaseDaoHibernate|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/persistence/BaseDAOHibernate.java.html] and implement PersonDAO. ''Javadocs eliminated for brevity.''
package org.appfuse.persistence.hibernate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.model.Person;
import org.appfuse.persistence.PersonDao;
import java.util.List;
public class PersonDaoHibernate extends BaseDaoHibernate implements PersonDao {
private Log log = LogFactory.getLog(PersonDaoHibernate.class);
public List getPeople(Person person) {
return getHibernateTemplate().find("from Person");
public Person getPerson(Long id) {
return (Person) getHibernateTemplate().get(Person.class, id);
public void savePerson(Object person) {
public void removePerson(Long id) {
Object person = getHibernateTemplate().load(Person.class, id);
You'll notice here that we're doing nothing with the ''person'' parameter. This is just a placeholder for now - in the future you may want to filter on it's properties using [Hibernate's Query Language|http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html] (HQL) or using [Criteria Queries|http://www.hibernate.org/hib_docs/reference/en/html/querycriteria.html].
''An example using a Criteria Query:''
Example example = Example.create(person)
.excludeZeroes() //exclude zero valued properties
.ignoreCase(); //perform case insensitive string comparisons
try {
return getSession().createCriteria(Person.class)
} catch (Exception e) {
throw new DAOException(e);
return new ArrayList();
Now, if you try to run "ant test-dao -Dtestcase=PersonDao", you will get the same error. We need to configure Spring so it knows that PersonDaoHibernate is the implementation of PersonDAO, and we also need to tell it about the Person object.
!!Configure Spring for the Person object and PersonDao [#5]
First, we need to tell Spring where the Hibernate mapping file is located. To do this, open src/dao/**/persistence/hibernate/applicationContext-hibernate.xml and add {{Person.hbm.xml}} to the following code block.
<property name="mappingResources">
Now we need to add some XML to this file to bind PersonDaoHibernate to PersonDao. To do this, add the following at the bottom of the file:
<!-- PersonDao: Hibernate implementation -->
<bean id="personDao" class="org.appfuse.persistence.hibernate.PersonDaoHibernate">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
;:''You could also use __autowire="byName"__ to the &lt;bean&gt; and get rid of the "sessionFactory" property. Personally, I like having the dependencies of my objects documented (in XML).''
!!Run the DaoTest [#6]
Save all your edited files and try running "ant test-dao -Dtestcase=PersonDao" one more time.
__Yeah Baby, Yeah:__
%%(color:green)BUILD SUCCESSFUL\\
Total time: 14 seconds%%
''Next Up:'' __Part II:__ [Creating new Managers|CreateManager] - A HowTo for creating [Business Delegates|http://java.sun.com/blueprints/corej2eepatterns/Patterns/BusinessDelegate.html] that talk to the database tier (DAOs) and the web tier (Struts Actions).

Back to SandBox, or to the Page History.