Raible's Wiki
Raible Designs AppFuseHomepage- Korean - Chinese - Italian - Japanese QuickStart Guide User Guide Tutorials Other ApplicationsStruts ResumeSecurity Example Struts Menu
Set your name in
UserPreferences
Referenced by
JSPWiki v2.2.33
Hide Menu |
This is version 25.
It is not the current version, and thus it cannot be edited. Part I: Creating new DAOs and Objects in AppFuse - A HowTo for creating Java Objects (that represent tables) and creating Java classes to persist those objects in the database. About this TutorialThis 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). This object basically represents a database table. The other classes will be:
AppFuse uses Hibernate 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.
Let's get started on creating a new Object, DAO and Test in AppFuse's architecture. Table of Contents
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/ejb/**/persistence directory) that has an id, a firstName and a lastName (as properties).
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. 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 tag that tells Hibernate what table this object relates to:
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.
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] id BIGINT NOT NULL AUTO_INCREMENT, [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/ejb/gen/**/persistence directory. Here's the contents of Person.hbm.xml (so far):
Now we'll add additional @hibernate.property tags for our other columns (firstName, 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 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". 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 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/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.
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 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 <junit> 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:
<table name='person'> <column>id</column> <column>first_name</column> <column>last_name</column> <row> <value>1</value> <value>Matt</value> <value>Raible</value> </row> </table>
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=RaibleThen, rather than calling person.set* to populate your objects, you can use the BaseDaoTestCase.populate(java.lang.Object) method:
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/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 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: DAOException: no DAOHibernate 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.
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. Notify Hibernate that this object exists [#5]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:
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:
Run the DaoTest [#6]Save all your edited files and try running "ant test-ejb -Dtestcase=PersonDao" one more time.Yeah Baby, Yeah:
BUILD SUCCESSFUL Next Up: Part II: Creating new Managers - A HowTo for creating Business Delegates that talk to the database tier (DAOs) and the web tier (Struts Actions).
|