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 148 and version 121:

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 removed 9 lines.
%%note __NOTE:__ If you're using MySQL and you want to use transactions (which you probably will) you have to use InnoDB tables. To do this, add the following to your mysql configuration file ({{/etc/my.cnf}} or {{c:\Windows\my.ini}}). The 2nd setting (for a UTF-8 character set) is needed for 4.1.7+.
{{{
[mysqld]
default-table-type=innodb
default-character-set=utf8
}}}
If you're using PostgreSQL and you get confusing errors about batch processing, try turning it off by adding {{<prop key="hibernate.jdbc.batch_size">0</prop>}} to your {{src/dao/**/hibernate/applicationContext-hibernate.xml}} file.
%%
At line 22 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. ;-)''
;:''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 24 removed 1 line.
At line 27 changed 2 lines.
;:References to files, directories and packages which exist in your source tree: {{build.xml}}.
;:%%(color: blue)''Suggestions for how to do stuff in the "Real World" like this.''%%
;: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 30 removed 2 lines.
At line 44 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/dao/**/model}} 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).
At line 34 added 2 lines.
%%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 51 changed 3 lines.
private Long id;
private String firstName;
private String lastName;
private Long id;
private String firstName;
private String lastName;
At line 63 changed 1 line.
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. 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.
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 65 changed 1 line.
;:''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], but I haven't tried it personally.''
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 67 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 &rarr; tables and properties (variables) &rarr; columns.
;:''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.''
At line 69 changed 1 line.
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:
%%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.%%
At line 61 added 4 lines.
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 &rarr; tables and properties (variables) &rarr; 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:
At line 79 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 85 changed 2 lines.
* @hibernate.id column="id"
* generator-class="increment" unsaved-value="null"
* @hibernate.id column="id" generator-class="increment" unsaved-value="null"
At line 94 changed 1 line.
;:%%(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__. This tutorial uses increment.''%%
;:%%(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 107 removed 1 line.
At line 110 changed 2 lines.
<?xml version="1.0"?>
<?xml version="1.0" encoding="UTF-8"?>
At line 113 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 145 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 (first_name, last_name):
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 164 changed 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.
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.
At line 179 changed 2 lines.
<div class="note" style="font-size: 12px">
<a name="appgen"></a>__The AppGen Tool__
%%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 182 changed 1 line.
As part of 1.6.1, I created an __AppGen__ tool that can be used to generate all the classes for the rest of these tutorials. This tool was based on contributions from [Lance Lavandowska|https://appfuse.dev.java.net/issues/show_bug.cgi?id=60] and [Ben Gill|https://appfuse.dev.java.net/issues/show_bug.cgi?id=78]. At first, I didn't want to add a code-generation feature like this b/c you'd end up with a 1-to-1 relationship between tables/pojos, DAOs and Managers. On most of my projects, I have far fewer DAOs and Managers than POJOs.
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.
At line 184 changed 1 line.
By default, AppGen will generate only Actions/Controllers, Action/Controller Tests, test data, i18n keys and JSPs. It will also configure Actions/Controllers for you. It uses the generic BaseManager and BaseDaoHibernate classes (configured as "manager" and "dao") to reduce the number of files that are generated. However, I realize that sometimes you will want to generate all the DAO and Manager classes (as well as their tests), so I've added that option too.
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 186 removed 18 lines.
To use the AppGen tool (after installing your web framework), perform the following steps:
# Create your POJO (in the model directory) and <a href="#ref-CreateDAO-5">configure the mapping file</a> in {{applicationContext-hibernate.xml}}.
# cd into the ''{{extras/appgen}}'' directory and run __ant -Dobject.name=Person -Dappgen.type=pojo__. In this example, the __Person__ class should exist in your {{model}} package. This generates all the files you create in the tutorials on this site (for your chosen web framework).
# To install the generated files, run __ant install__. You can run __ant install -Dmodel.name=Person -Dmodel.name.lowercase=person__ if you want to do everything in one fell swoop. __WARNING:__ You might want to backup your project before you do this - or at least make sure it's checked into a source code repository. I've tested this code, and I think it works well - but it ''is'' modifying your source tree for you.
The reason for the "lowercase" parameter is to rename the JSPs to begin with a lowercase letter. If I tried to rename them and change the filename programmatically, it took 1MB worth of BSF and Rhino JARs (+5 lines of code) and this just seemed easier. Speaking of JSPs - it's up to you to modify the {{*Form.jsp}} and make it look pretty. This is covered in Step 5 of each respective web framework's "Create Action/Controller" tutorial: <a href="http://raibledesigns.com/wiki/Wiki.jsp?page=CreateActions#ref-CreateAction-5">Struts</a>, <a href="http://raibledesigns.com/wiki/Wiki.jsp?page=SpringControllers#ref-SpringControllers-5">Spring</a> and <a href="http://raibledesigns.com/wiki/Wiki.jsp?page=WebWorkActions#ref-WebWorkActions-5">WebWork</a>.
__NOTE:__ If you'd like to generate all the DAOs/Managers/Tests, run __ant install-detailed__ instead of __ant install__. Before you install anything, the files will be created in the {{extras/appgen/build/gen}} directory (in case you want to look at them before installing). If you just want to test the tool, you can cd to this directory and run __ant test__ to see the contents of these tutorials created.
I encourage you to read these tutorials even if you decide to generate all your code. That way you'll understand what's being generated for you and you'll only need to mailing list for [asking smart questions|http://www.catb.org/~esr/faqs/smart-questions.html]. ;-) Hopefully this tool will remove the pain of writing simple CRUD code and let you concentrate on developing your business logic and fancy UIs!</div>
Now we'll create a DaoTest to test that 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/**/dao}} directory. This class should extend [BaseDaoTestCase|http://raibledesigns.com/downloads/appfuse/api/org/appfuse/dao/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 (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.
;:%%(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.''%%
At line 216 changed 3 lines.
protected void setUp() throws Exception {
super.setUp();
dao = (PersonDao) ctx.getBean("personDao");
public void setPersonDao(PersonDao dao) {
this.dao = dao;
At line 220 removed 7 lines.
protected void tearDown() throws Exception {
super.tearDown();
dao = null;
}
At line 230 changed 1 line.
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/dao/BaseDaoTestCase.java.html] class.
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.
At line 232 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 &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:
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 &lt;junit&gt; 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 289 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 the 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:''%%
;:%%(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:''%%
At line 308 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 {{PersonDaoTest.java}} and define your property values inside it:
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:
At line 322 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 325 changed 1 line.
First off, create a PersonDao.java interface in the {{src/dao/**/dao}} 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 340 changed 1 line.
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.
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 344 changed 1 line.
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/BaseDAOHibernate.java.html] and implement PersonDAO. ''Javadocs eliminated for brevity.''
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 360 changed 1 line.
throw new ObjectRetrievalFailureException(Person.class, id);
throw new ObjectRetrievalFailureException(Person.class, id);
At line 371 removed 1 line.
At line 378 changed 1 line.
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.
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.
At line 382 changed 1 line.
First, we 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.
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 390 changed 2 lines.
<value>org/appfuse/model/User.hbm.xml</value>
<value>org/appfuse/model/UserCookie.hbm.xml</value>
<value>org/appfuse/model/User.hbm.xml</value>
At line 396 changed 1 line.
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:
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 402 changed 1 line.
<property name="sessionFactory"><ref local="sessionFactory"/></property>
<property name="sessionFactory" ref="sessionFactory"/>
At line 406 changed 1 line.
;:''You could also use __autowire="byName"__ to the &lt;bean&gt; and get rid of the "sessionFactory" property''. %%(color: blue)''Personally, I like having the dependencies of my objects documented (in XML).''%%
%%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.%%

Back to CreateDAO, or to the Page History.