At line 1 changed 1 line. |
__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. |
__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. |
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. |
!!About this tutorial |
This tutorial will show you how to create a new table in the database, and how the create Java code to access this table. |
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: |
You will create an object and then some more classes to persist (save/retrieve/delete) that object from the database. In Java speak, this object is called 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 9 changed 1 line. |
* A [JUnit|http://www.junit.org] class to test our DAO is working |
* A [JUnit|http://www.junit.org] class to test the DAO is working |
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. |
AppFuse uses [Hibernate|http://www.hibernate.org] for its default 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. |
At line 13 changed 1 line. |
;:%%(color: blue)''I will tell you how I do stuff in the __Real World__ in text like this.''%% |
;:''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}}. Then complete the [iBATIS version of this tutorial|CreateDAOiBATIS].'' |
At line 15 changed 1 line. |
Let's get started on creating a new Object, DAO and Test in AppFuse's architecture. |
!Font Conventions (work in progress) |
;:Literal strings intended to be executed at the command prompt look like this: __ant test-all__. |
;:References to files, directories and packages which exist in your source tree: <font size="2">{{build.xml}}</font>. |
;:%%(color: blue)''And suggestions for how to do stuff in the "Real World" are in blue italics.''%% |
At line 20 added 2 lines. |
Let's get started on creating a new Object, DAO and Test in AppFuse's project structure. |
|
At line 22 changed 1 line. |
* [5] Notify Hibernate that this object exists in ServiceLocator (for tests) and in hibernate.cfg.xml (for webapp) |
* [5] Configure Spring for the Person object and PersonDao |
At line 26 changed 1 line. |
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). |
|
The first thing you need to do is create an object to persist. Create a simple "Person" object (in the {{src/dao/**/model}} directory) that has an id, a firstName and a lastName (as properties). |
|
%%note __NOTE:__ Copying the Java code in these tutorials [doesn't work in Firefox|http://raibledesigns.com/page/rd?anchor=java2html_plugin_for_jspwiki_causes]. A workaround is to CTRL+Click (Command+Click on OS X) the code block and then copy it.%% |
|
At line 28 removed 1 line. |
package org.appfuse.persistence; |
At line 38 added 2 lines. |
package org.appfuse.model; |
|
At line 31 changed 3 lines. |
private Long id; |
private String firstName; |
private String lastName; |
private Long id; |
private String firstName; |
private String lastName; |
At line 42 removed 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 44 changed 2 lines. |
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. |
This class should extend [BaseObject|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/model/BaseObject.java.html], which has 3 abstract methods: (equals(), hashCode() and toString()) that you will need to implement in the Person class. The first two are required by Hibernate. If you plan to put this object into the user's session, or expose it through a web service, you should implement {{java.io.Serializable}} as well. |
At line 47 changed 1 line. |
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. |
The easiest way to do this is using [Commonclipse|http://commonclipse.sf.net]. More information on using this tool can be found on [Lee Grey's site|http://www.leegrey.com/hmm/2004/09/29/1096491256000.html]. Another Eclipse Plugin you can use is [Commons4E|http://commons4e.berlios.de/]. I haven't used it, so I can't comment on its functionality. |
At line 49 changed 2 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: |
[{Java2HtmlPlugin |
;:''If you're using [IntelliJ IDEA|http://www.jetbrains.com/idea], you can generate equals() and hashCode(), but not toString(). There is a [ToStringPlugin|http://www.intellij.org/twiki/bin/view/Main/ToStringPlugin] that works reasonably well.'' |
|
%%note __NOTE:__ If installing these plugins doesn't work for you, you can find all of these methods in the Person.java object that's used to test AppGen. Just look in ''extras/appgen/test/dao/org/appfuse/model/Person.java'' and copy and paste the methods from that class.%% |
|
Now that you have this POJO created, you 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, 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: |
|
[{Java2HtmlPlugin |
|
At line 52 removed 1 line. |
* @author mraible |
At line 58 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. |
You 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. |
|
At line 76 added 1 line. |
|
At line 62 changed 2 lines. |
* @hibernate.id column="id" |
* generator-class="native" unsaved-value="null" |
* @hibernate.id column="id" generator-class="increment" unsaved-value="null" |
At line 70 removed 1 line. |
;:%%(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 87 added 2 lines. |
;:%%(color: blue)''I'm using {{generator-class="increment"}} instead of {{generator-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__. This tutorial uses increment.''%% |
|
At line 73 changed 2 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: |
[{Java2HtmlPlugin |
At this point, you can 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 you: |
{{{ |
At line 76 changed 1 line. |
[schemaexport] id BIGINT NOT NULL AUTO_INCREMENT, |
[schemaexport] id bigint not null, |
At line 78 changed 2 lines. |
[schemaexport] ) |
}] |
[schemaexport] ); |
}}} |
At line 81 changed 1 line. |
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): |
If you want to look at the {{Person.hbm.xml}} file that Hibernate generates for you, look in the {{build/dao/gen/**/model}} directory. Here's the contents of {{Person.hbm.xml}} (so far): |
|
At line 83 removed 1 line. |
<?xml version="1.0"?> |
At line 102 added 1 line. |
<?xml version="1.0" encoding="UTF-8"?> |
At line 86 changed 2 lines. |
"-//Hibernate/Hibernate Mapping DTD 2.0//EN" |
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> |
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" |
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> |
At line 91 changed 1 line. |
name="org.appfuse.persistence.Person" |
name="org.appfuse.model.Person" |
At line 103 changed 1 line. |
<generator class="native"> |
<generator class="increment"> |
At line 118 changed 1 line. |
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): |
Now you'll add additional [@hibernate.property|http://xdoclet.sourceforge.net/tags/hibernate-tags.html#@hibernate.property%20(0..1)] tags for the other columns (first_name, last_name): |
|
At line 139 added 1 line. |
|
At line 121 changed 2 lines. |
* @return Returns the firstName. |
* @hibernate.property column="first_name" |
* @hibernate.property column="first_name" length="50" |
At line 129 changed 2 lines. |
* @return Returns the lastName. |
* @hibernate.property column="last_name" |
* @hibernate.property column="last_name" length="50" |
At line 136 removed 1 line. |
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. |
At line 138 changed 6 lines. |
Run "ant setup-db" again to get the additional columns added to your table. |
[{Java2HtmlPlugin |
[schemaexport] create table person ( |
[schemaexport] id BIGINT NOT NULL AUTO_INCREMENT, |
[schemaexport] first_name VARCHAR(255), |
[schemaexport] last_name VARCHAR(255), |
In this example, the only reason for adding the ''column'' attribute is because the column name is different from the 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(50), |
[schemaexport] last_name varchar(50), |
At line 145 changed 3 lines. |
[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". |
[schemaexport] );}}} |
At line 166 added 2 lines. |
If you want to change the size of your columns, modify the ''length'' attribute in your @hibernate.property tag. If you want to make it a required field (NOT NULL), add not-null="true". |
|
At line 150 removed 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 152 changed 1 line. |
To start, create a PersonDaoTest.java class in the test/ejb/**/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 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. |
%%note <a name="appgen"></a>__NOTE:__ AppFuse versions 1.6.1+ contain include an [AppGen] tool that can be used to generate all the classes for the rest of these tutorials. However, it's best that you go through these tutorials before using this tool - then you'll know what code it's generating.%% |
At line 154 changed 1 line. |
;:%%(color: blue)''I usually copy (open → 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.''%% |
Now you'll create a DaoTest to test that your DAO works. "Wait a minute," you say, "I 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/**/dao}} directory. This class should extend [BaseDaoTestCase|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/dao/BaseDaoTestCase.java.html], a subclass of Spring's [AbstractTransactionalDataSourceSpringContextTests|http://www.springframework.org/docs/api/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.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 (optionally) 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. |
|
At line 156 removed 1 line. |
package org.appfuse.persistence; |
At line 158 changed 2 lines. |
import org.apache.commons.logging.Log; |
import org.apache.commons.logging.LogFactory; |
package org.appfuse.dao; |
At line 180 added 3 lines. |
import org.appfuse.model.Person; |
import org.springframework.dao.DataAccessException; |
|
At line 163 removed 2 lines. |
//~ Instance fields ======================================================== |
private Log log = LogFactory.getLog(PersonDaoTest.class); |
At line 168 changed 3 lines. |
//~ Constructors =========================================================== |
public PersonDaoTest(String name) { |
super(name); |
public void setPersonDao(PersonDao dao) { |
this.dao = dao; |
At line 172 removed 16 lines. |
|
//~ 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); |
} |
At line 190 removed 1 line. |
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. |
At line 192 changed 1 line. |
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: |
The code you see above is what you need for a basic Spring integration test that initializes and configures an implementation of PersonDao. Spring will use autowiring byType to call the ''setPersonDao()'' method and set the "personDao" bean as a dependency of this class. |
|
Now you need test that the CRUD (create, retrieve, update, delete) methods work in your DAO. To do this, create 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 the <junit> task in build.xml. Below are 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: |
|
At line 199 added 1 line. |
|
At line 195 changed 8 lines. |
person = new Person(); |
person.setFirstName("Matt"); |
person.setLastName("Raible"); |
|
dao.savePerson(person); |
dao.getPerson(person.getId()); |
log.info(person); |
assertTrue(person.getFirstName() != null); |
person = new Person(); |
person.setFirstName("Matt"); |
person.setLastName("Raible"); |
|
dao.savePerson(person); |
assertNotNull(person.getId()); |
|
person = dao.getPerson(person.getId()); |
assertEquals(person.getFirstName(), "Matt"); |
At line 215 added 1 line. |
|
At line 216 changed 1 line. |
assertTrue(person.getLastName().equals("Last Name Updated")); |
assertEquals(person.getLastName(), "Last Name Updated"); |
At line 225 removed 3 lines. |
|
assertTrue(person.getFirstName().equals("Bill")); |
assertTrue(person.getId() != null); |
At line 234 added 3 lines. |
assertEquals(person.getFirstName(), "Bill"); |
assertNotNull(person.getId()); |
|
At line 233 changed 1 line. |
dao.removePerson(person); |
dao.removePerson(person.getId()); |
|
try { |
person = dao.getPerson(person.getId()); |
fail("Person found in database"); |
} catch (DataAccessException dae) { |
log.debug("Expected exception: " + dae.getMessage()); |
assertNotNull(dae); |
} |
At line 237 changed 3 lines. |
;:%%(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="margin-left: 50px"> |
[{Java2HtmlPlugin |
;:%%(color: blue)''In the testGetPerson method, you'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 the database with test data before the tests are run, you can simply add the new table/record to the metadata/sql/sample-data.xml file:''%% |
|
<div style="color: blue !important; margin-left: 50px"> |
{{{ |
At line 242 changed 2 lines. |
<column>firstName</column> |
<column>lastName</column> |
<column>first_name</column> |
<column>last_name</column> |
At line 250 changed 1 line. |
}] |
}}} |
At line 252 removed 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".''%% |
At line 254 changed 1 line. |
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: |
;:%%(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 person.set*(value) is being called to populate the Person object before saving it. This is easy in this example, but it could get quite cumbersome if you'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 {{PersonDaoTest.java}} and define your property values inside it: |
;:%%(color: blue)''I tend to just hard-code test values into Java code - but the .properties file is an option that works great for large objects.''%% |
At line 279 added 1 line. |
|
At line 281 added 1 line. |
|
At line 265 changed 2 lines. |
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 this point, the PersonDaoTest class won't compile yet because there is no PersonDao.class in your classpath, you need to create it. PersonDao.java is an interface, and PersonDaoHibernate.java is the Hibernate implementation of that interface. |
At line 268 changed 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.'' |
First off, create a PersonDao.java interface in the {{src/dao/**/dao}} directory and specify the basic CRUD methods for any implementation classes. |
|
At line 270 removed 1 line. |
package org.appfuse.persistence; |
At line 272 changed 1 line. |
public interface PersonDao extends Dao { |
package org.appfuse.dao; |
At line 274 changed 1 line. |
public Person getPerson(Long personId) throws DAOException; |
import org.appfuse.model.Person; |
At line 276 changed 3 lines. |
public void savePerson(Person Person) throws DAOException; |
|
public void removePerson(Person Person) throws DAOException; |
public interface PersonDao extends Dao { |
public Person getPerson(Long personId); |
public void savePerson(Person person); |
public void removePerson(Long personId); |
At line 281 removed 1 line. |
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>. |
At line 283 changed 1 line. |
;:''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.'' |
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 you need to specify a bean named ''personDao'' in {{applicationContext-hibernate.xml}}. Before you do that, you need to create the PersonDao implementation class. |
At line 285 changed 1 line. |
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. |
;:''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/**/dao/hibernate}} and name it {{PersonDaoHibernate.java}}. It should extend [BaseDaoHibernate|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/dao/hibernate/BaseDaoHibernate.java.html] and implement PersonDao. ''Javadocs eliminated for brevity.'' |
|
At line 287 removed 1 line. |
package org.appfuse.persistence; |
At line 289 changed 1 line. |
import net.sf.hibernate.Session; |
package org.appfuse.dao.hibernate; |
At line 291 changed 2 lines. |
import org.apache.commons.logging.Log; |
import org.apache.commons.logging.LogFactory; |
import org.appfuse.model.Person; |
import org.appfuse.dao.PersonDao; |
import org.springframework.orm.ObjectRetrievalFailureException; |
At line 295 removed 2 lines. |
|
private Log log = LogFactory.getLog(PersonDaoHibernate.class); |
At line 298 changed 3 lines. |
public PersonDaoHibernate(Object conn) { |
this.ses = (Session) conn; |
} |
public Person getPerson(Long id) { |
Person person = (Person) getHibernateTemplate().get(Person.class, id); |
At line 302 changed 2 lines. |
public Person getPerson(Long id) throws DAOException { |
return (Person) retrieveObject(ses, Person.class, id); |
if (person == null) { |
throw new ObjectRetrievalFailureException(Person.class, id); |
} |
|
return person; |
At line 306 changed 2 lines. |
public void savePerson(Person person) throws DAOException { |
storeObject(ses, person); |
public void savePerson(Person person) { |
getHibernateTemplate().saveOrUpdate(person); |
At line 310 changed 2 lines. |
public void removePerson(Person user) throws DAOException { |
removeObject(ses, Person.class, user.getId(), user); |
public void removePerson(Long id) { |
// object must be loaded before it can be deleted |
getHibernateTemplate().delete(getPerson(id)); |
At line 315 removed 1 line. |
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 317 changed 2 lines. |
!!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: |
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 you also need to tell it about the Person object. |
|
!!Configure Spring for the Person object and PersonDao [#5] |
|
First, you need to tell Spring where the Hibernate mapping file is located. To do this, open {{src/dao/**/dao/hibernate/applicationContext-hibernate.xml}} and add {{"Person.hbm.xml"}} to the following code block. |
|
At line 320 changed 4 lines. |
sf = new Configuration().addClass(Person.class) |
.addClass(Role.class) |
.addClass(UserRole.class) |
.addClass(User.class).buildSessionFactory(); |
|
<property name="mappingResources"> |
<list> |
<value>org/appfuse/model/Person.hbm.xml</value> |
<value>org/appfuse/model/Role.hbm.xml</value> |
<value>org/appfuse/model/User.hbm.xml</value> |
</list> |
</property> |
At line 325 changed 1 line. |
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: |
|
Now you 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: |
|
At line 327 changed 4 lines. |
<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"/> |
|
<!-- PersonDao: Hibernate implementation --> |
<bean id="personDao" class="org.appfuse.dao.hibernate.PersonDaoHibernate"> |
<property name="sessionFactory" ref="sessionFactory"/> |
</bean> |
At line 367 added 2 lines. |
%%note __NOTE:__ Don't forget to correct the package name in the "class" attribute above if you specified a package other then org.appfuse when you created your project.%% |
|
At line 334 changed 1 line. |
Save all your edited files and try running "ant test-ejb -Dtestcase=PersonDao" one more time. |
Save all your edited files and try running __ant test-dao -Dtestcase=PersonDao__ one more time. |
At line 338 changed 1 line. |
Total time: 26 seconds%% |
Total time: 9 seconds%% |
At line 342 changed 1 line. |
''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). |
''Next Up:'' __Part II:__ [Creating new Managers|CreateManager] - A HowTo for creating Business Facades, which are similar to [Session Facades|http://java.sun.com/blueprints/patterns/SessionFacade.html], but don't use EJBs. These facades are used to provide communication from the front-end to the DAO layer. |