Raible's Wiki

Raible Designs
Wiki Home
News
Recent Changes

AppFuse

Homepage
  - Korean
  - Chinese
  - Italian
  - Japanese

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

User Guide
  - Korean
  - Chinese

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

FAQ
  - Korean

Latest Downloads

Other Applications

Struts Resume
Security Example
Struts Menu

Set your name in
UserPreferences


Referenced by
Articles
Articles_pt
CreateDAO_es
CreateDAO_pt
CreateDAO_sp
CreateDAOiBATIS
CreateManager
CreateManager_es
CreateManager_ko
CreateManager_zh
...and 3 more




JSPWiki v2.2.33

[RSS]


Hide Menu

CreateDAO


Difference between version 4 and version 3:

At line 2 changed 1 line.
This tutorial will show you how to create a new table in the database, and how to create Java code to access this table. 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:
This tutorial will show you how to create a new table in the database, and how to create Java code to access this table.
At line 4 changed 3 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
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:
* 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
At line 9 changed 3 lines.
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.
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.
;:%%(color: blue)''I will tell you how I do stuff in the __Real World__ in text like this.''%%
At line 18 changed 3 lines.
* [3] Create a new DAO to perform CRUD on the object
* [4] Notify Hibernate that this object exists in ServiceLocator (for tests) and in hibernate.cfg.xml (for webapp)
* [5] Run the DaoTest
* [4] Create a new DAO to perform CRUD on the object
* [5] Notify Hibernate that this object exists in ServiceLocator (for tests) and in hibernate.cfg.xml (for webapp)
* [6] Run the DaoTest
At line 23 changed 3 lines.
The first thing we need to do is create an object to persist. Let's create a simple "Person"
object that has an id, a firstName and a lastName (as properties).
The first thing we need to do is create an object to persist. Let's create a simple "Person" object (in the src/ejb/**/persistence directory) that has an id, a firstName and a lastName (as properties).
At line 33 changed 7 lines.
/*
Generate your getters and setters using
your favorite IDE:
Eclipse: Right-click -> Source - >
Generate Getters and Setters
IDEA: ?? I can't seem to figure it out right now
/*
* Generate your getters and setters using your favorite IDE:
* In Eclipse:
* Right-click -> Source -> Generate Getters and Setters
*/
At line 40 added 1 line.
;:%%(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.''%%
At line 43 changed 2 lines.
In the code snippet above, we're extending BaseObject because it has the following useful methods:
toString(), equals(), hashCode() - the latter two are required by Hibernate.
In the code snippet above, we're extending [BaseObject|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/persistence/BaseObject.java.html] because it has the following useful methods: toString(), equals(), hashCode() - the latter two
are required by Hibernate.
At line 46 changed 2 lines.
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.
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.
At line 47 added 22 lines.
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:
{{{
/**
* @author mraible
* @hibernate.class table="person"
*/
public class Person extends BaseObject {
}}}
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.
{{{
/**
* @return Returns the id.
* @hibernate.id column="id"
* generator-class="native" unsaved-value="null"
*/
public Long getId() {
return this.id;
}
}}}
;:%%(color: blue)''I try to remember to add the Person object to ServiceLocator.java and hibernate.cfg.xml at this point. This is covered in [step 5|5].''%%
At line 70 added 7 lines.
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] id BIGINT NOT NULL AUTO_INCREMENT,
[schemaexport] primary key (id)
[schemaexport] )
}}}
At line 78 added 68 lines.
If you want to look at the Person.hbm.xml file that Hibernate generates for you, look in the build/ejb/gen/**/persistence 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"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class
name="org.appfuse.persistence.Person"
table="person"
dynamic-update="false"
dynamic-insert="false"
>
<id
name="id"
column="id"
type="java.lang.Long"
unsaved-value="null"
>
<generator class="native">
</generator>
</id>
<!--
To add non XDoclet property mappings, create a file named
hibernate-properties-Person.xml
containing the additional properties and place it in your merge dir.
-->
</class>
</hibernate-mapping>
}}}
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 (firstName, lastName):
{{{
/**
* @return Returns the firstName.
* @hibernate.property column="first_name"
*/
public String getFirstName() {
return this.firstName;
}
/**
* @return Returns the lastName.
* @hibernate.property column="last_name"
*/
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 AUTO_INCREMENT,
[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".
At line 147 added 1 line.
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.
At line 149 added 112 lines.
To start, create a PersonDaoTest.java class in the test/ejb/**/persistence directory. This class should extend BaseDaoTestCase, which already exists in this package. This parent class is mainly used 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 "rd" 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;
public class PersonDaoTest extends BaseDaoTestCase {
//~ Instance fields ========================================================
private Log log = LogFactory.getLog(PersonDaoTest.class);
private Person person = null;
private PersonDao dao = null;
//~ Constructors ===========================================================
public PersonDaoTest(String name) {
super(name);
}
//~ Methods ================================================================
protected void setUp() throws Exception {
super.setUp();
dao = (PersonDao) DAOFactory.getInstance(conn, PersonDao.class);
}
protected void tearDown() throws Exception {
dao = null;
super.tearDown();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(PersonDaoTest.class);
}
}
}}}
The code you see above is what we need for a basic JUnit test that initializes and destroys our PersonDao. The "conn" object is initialized (and obtains a connection) in the [BaseDaoTestCase|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.setFirstName("Matt");
person.setLastName("Raible");
dao.savePerson(person);
dao.getPerson(person.getId());
log.info(person);
assertTrue(person.getFirstName() != null);
}
public void testSavePerson() throws Exception {
person = dao.getPerson(new Long(1));
person.setFirstName("Matt");
person.setLastName("Last Name Updated");
dao.savePerson(person);
if (log.isDebugEnabled()) {
log.debug("updated Person: " + person);
}
assertTrue(person.getLastName().equals("Last Name Updated"));
}
public void testAddAndRemovePerson() throws Exception {
person = new Person();
person.setFirstName("Bill");
person.setLastName("Joy");
dao.savePerson(person);
assertTrue(person.getFirstName().equals("Bill"));
assertTrue(person.getId() != null);
if (log.isDebugEnabled()) {
log.debug("removing person...");
}
dao.removePerson(person);
}
}}}
;:%%(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:''%%
<div style="color: blue; margin-left: 50px">
{{{<table name='person'>
<column>id</column>
<column>firstName</column>
<column>lastName</column>
<row>
<value>1</value>
<value>Matt</value>
<value>Raible</value>
</row>
</table>
}}}
</div>
;:%%(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".''%%
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:
{{{
firstName=Matt
lastName=Raible
}}}
Then, rather than calling person.set* to populate your objects, you can use the BaseDaoTestCase.populate(java.lang.Object) method:
{{{
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.
At line 262 added 1 line.
First off, create a PersonDao.java interface in the src/ejb/**/persistence directory and specify the basic CRUD methods for any implementation classes. ''I've eliminated the JavaDocs in the class below for display purposes.''
At line 264 added 47 lines.
{{{package org.appfuse.persistence;
public interface PersonDao extends Dao {
public Person getPerson(Long personId) throws DAOException;
public void savePerson(Person Person) throws DAOException;
public void removePerson(Person Person) throws DAOException;
}
}}}
At this point, you should be able to compile all the source in src/ejb and test/ejb using "ant compile-ejb". However, if you try to run "ant test-ejb -Dtestcase=PersonDao", you will get an error: <span style="color: red">DAOException: no DAOHibernate class</span>.
;:''The ant task for running tests is called "test-module." 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 squash that bug and create 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/ejb/**/persistence and name it PersonDAOHibernate.java. It should extend BaseDaoHibernate and implement PersonDAO.
{{{
package org.appfuse.persistence;
import net.sf.hibernate.Session;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PersonDaoHibernate extends BaseDaoHibernate implements PersonDao {
private Log log = LogFactory.getLog(PersonDaoHibernate.class);
public PersonDaoHibernate(Object conn) {
this.ses = (Session) conn;
}
public Person getPerson(Long id) throws DAOException {
return (Person) retrieveObject(ses, Person.class, id);
}
public void savePerson(Person person) throws DAOException {
storeObject(ses, person);
}
public void removePerson(Person user) throws DAOException {
removeObject(ses, Person.class, user.getId(), user);
}
}
}}}
Now, if you try to run "ant test-ejb -Dtestcase=PersonDao", you will get an error that no Persister was found for the Person object, which brings us to the final step.
At line 312 added 14 lines.
We have to tell Hibernate that this Person is persistable. For the JUnit tests, this is done in the src/ejb/**/persistence/ServiceLocator.java class. Simply add this class to the list of existing classes in the following code block:
{{{
sf = new Configuration().addClass(Person.class)
.addClass(Role.class)
.addClass(UserRole.class)
.addClass(User.class).buildSessionFactory();
}}}
The JUnit tests use the database.properties file to initialize a Hibernate database connection, whereas Tomcat uses JNDI. Therefore, we must edit a different file for Tomcat: web/WEB-INF/classes/hibernate.cfg.xml. Add a new line for the Person.hbm.xml file in the following XML fragment:
{{{
<mapping resource="org/appfuse/persistence/Person.hbm.xml"/>
<mapping resource="org/appfuse/persistence/Role.hbm.xml"/>
<mapping resource="org/appfuse/persistence/User.hbm.xml"/>
<mapping resource="org/appfuse/persistence/UserRole.hbm.xml"/>
}}}
At line 328 added 5 lines.
Save all your edited files and try running "ant test-ejb -Dtestcase=PersonDao" one more time.
__Yeah Baby, Yeah:__
%%(color:green)BUILD SUCCESSFUL\\
Total time: 26 seconds%%

Back to CreateDAO, or to the Page History.