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 11.
It is not the current version, and thus it cannot be edited. Part I: Neue DAOs und Objekte in AppFuse anlegen - Eine Anleitung zum Erstellen von Java Objekten (welche Tabellen darstellen) und Java Klassen, um diese Objekte persistent in einer Datenbank abzulegen. Über dieses TutorialDieses Tutorial erläutert, wie man eine neue Tabelle in der Datenbank anlegt und wie man Java Code erzeugt, um auf diese Tabelle zuzugreifen.Zuerst werden wir ein Objekt erstellen und anschliessend weitere Klassen, um dieses Objekt in eine Datenbank zu speichern, wieder auszulesen und zu löschen. In der Java Sprache nennt sich dieses Objekt ein Plain Old Java Object (auch bekannt als POJO). Dieses Objekt stellt hauptsächlich eine Datenbanktabelle dar. Die anderen Klassen sind folgende:
[mysqld] default-table-type=innodb default-character-set=utf8 Wenn man PostgreSQL nutzt und komische Fehlermeldungen über batch processing erhält, kann man versuchen dies abzustellen indem man die Zeile <prop key="hibernate.jdbc.batch_size">0</prop> zur Datei src/dao/**/hibernate/applicationContext-hibernate.xml hinzufügt. AppFuse nutzt Hibernate als Standard Persistenz Schicht. Hibernate ist ein Object/Relational (O/R) Framework, welches es einem ermöglicht, Java Objekte und Datenbanktabellen zu verknüpfen. Das Framework erlaubt es einem, sehr einfach CRUD (Create, Retrieve, Update, Delete) Methoden auf seine Objekte anzuwenden.
Font Konventionen (in Arbeit)
Beginnen wir mit dem Erstellen eines neuen Objekts, der DAO Klasse und der Tests in Appfuse Projekt Struktur. Inhaltsverzeichnis
Ein neues Objekt erzeugen und XDoclet tags hinzufügen [#1]Als Erstes benötigen wir ein Objekt. welches wir persistent speichern wollen. Dafür erzeugen wir ein einfaches "Person" Objekt (im src/dao/**/model Verzeichnis), welches eine ID, einen Vornamen und einen Nachnamen (als Properties) besitzt. Bemerkung: Der Java Code in diesem Tutorial kann man nicht mit mit dem Firefox Browser kopieren. Als Notlösung führt man CTRL+Click (Command+Click mit OS X) auf dem Code Block aus und kopiert ihn anschliessend.
This class should extend BaseObject, 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. More information on using this tool can be found on Lee Grey's site. Another Eclipse Plugin you can use is Commons4E. I haven't used it, so I can't comment on its functionality.
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.
Aus dem Objekt mit Hilfe von Ant eine neue Datenbanktabelle erzeugen [#2]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:[schemaexport] create table person ( [schemaexport] id bigint not null, [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/**/model directory. Here's the contents of Person.hbm.xml (so far):
Now we'll add additional @hibernate.property tags for our other columns (first_name, last_name):
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, [schemaexport] first_name varchar(50), [schemaexport] last_name varchar(50), [schemaexport] primary key (id) [schemaexport] ); 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". Eine neuen DaoTest erzeugen, um die DAO Klasse mit Hilfe von JUnit zu testen [#3]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.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 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, a subclass of Spring's AbstractDependencyInjectionSpringContextTests which already exists in this package. This parent class is used to load Spring's 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.
The code you see above is what we need for a basic Spring integration test that initializes and destroys our PersonDao. Spring will use autowiring byType to call the setPersonDao() method and set the "personDao" bean as a dependency of this 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 PersonDaoTest.java 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. Eine neue DAO Klasse erzuegen, um CRUD Methoden auf dem Objekt auszuführen [#4]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.
Notice in the class above there are no exceptions on the method signatures. This is due to the power of Spring 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: No bean named 'personDao' is defined. 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.
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 and implement PersonDAO. Javadocs eliminated for brevity.
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. Spring für das Person Objekt und die PersonDao konfigurieren [#5]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.
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:
Den DaoTest ausführen [#6]Save all your edited files and try running ant test-dao -Dtestcase=PersonDao one more time.Yeah Baby, Yeah:
BUILD SUCCESSFUL Next Up: Part II: Creating new Managers - A HowTo for creating Business Facades, which are similar to Session Facades, but don't use EJBs. These facades are used to provide communication from the front-end to the DAO layer.
|