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
CreateManager_it
LeftMenu




JSPWiki v2.2.33

[RSS]


Hide Menu

CreateDAO_it


This is version 2. It is not the current version, and thus it cannot be edited.
[Back to current version]   [Restore this version]


Parte I: Creare nuovi DAO ed Object in AppFuse - Un HowTo su come creare Java Object (che rappresentino tabelle) e creare classi Java per rendere persistenti tali oggetti nel database.

Informazioni su questo tutorial

Questo tutorial mostrerà come creare un nuova tabella nel database, e come creare il codice Java per accedere a questa tabella.

Verrà creato un oggetto e poi delle altre classi per rendere persistente (registrare/recuperare/eliminare) quell'oggetto dal database. Parlando in Java, questo oggetto viene chiamato Plain Old Java Object (a.k.a. POJO). Questo oggetto in sostanza rappresenta una tabella su database. Le altre classi saranno:

  • Un Data Access Object (a.k.a. DAO), un'Interfaccia ed un'Implementazione su Hibernate
  • Una classe JUnit per verificare che il DAO funziona

AppFuse usa Hibernate come layer di persistenza di default. Hibernate è un Object/Relational (O/R) Framework che permette di correlare i tuoi Java Object alle tabelle del database. Ti permette di effettuare molto facilmente operazioni CRUD (Create, Retrieve, Update, Delete) sui tuoi oggetti.

Puoi usare anche iBATIS come scelta di persistence framework. Per installare iBATIS in AppFuse, vedere il file README.txt in extras/ibatis. Poi completa la versione iBATIS di questo tutorial.

Convenzioni Tipografiche (work in progress)

Le stringhe di testo da intendersi eseguite al prompt dei comandi si presentano così: ant test-all.
Riferimenti a file, directory e package all'interno dell'alberatura del tuo sorgente: build.xml.
E suggerimenti su come fare le cose nel "Mondo Reale" sono in corsivo blu.

Iniziamo a creare un nuovo Object, DAO e Test nella struttura di progetto di AppFuse.

Indice

  • [1] Creare un nuovo Object ed aggiungere i tag XDoclet
  • [2] Creare un nuova tabella nel database a partire dall'oggetto usando Ant
  • [3] Creare un nuovo DaoTest per eseguire i test JUnit sul DAO
  • [4] Creare un nuovo DAO per effettuare operazioni CRUD sull'oggetto
  • [5] Configurare Spring per l'oggetto Person e il PersonDao
  • [6] Eseguire il DaoTest

Creare un nuovo Object ed aggiungere i tag XDoclet [#1]

La prima cosa che devi fare è creare un oggetto da rendere persistente. Crea un semplice oggetto "Person" (nella directory src/dao/**/model) che abbia un id, un firstName ed un lastName (come proprietà).

NOTA: La copia del codice Java in questi tutorial non funziona in Firefox. Un workaround è usare CTRL+Clic (Comando+Clic su OS X) sul blocco di codice e poi copiarlo.


package org.appfuse.model;

public class Person extends BaseObject {
    private Long id;
    private String firstName;
    private String lastName;

    /*
     Generate your getters and setters using your favorite IDE: 
     In Eclipse:
     Right-click -> Source -> Generate Getters and Setters
    */
}

Questa classe deve estendere BaseObject, che ha 3 metodi astratti: (equals(), hashCode() e toString()) che dovrai implementarre per la classe Person. I primi due sono richiesti da Hibernate. Il modo più facile per farlo è usare Commonclipse. Ulteriori informazioni sull'uso di questo strumento si possono trovare sul sito di Lee Grey. Un altro Plugin di Eclipse che puoi usare è Commons4E. Non l'ho usato, per cui non posso fare commenti sulle sul suo funzionamento.

Se stai usando IntelliJ IDEA, puoi generare i metodi equals() e hashCode(), ma non il toString(). C'è un ToStringPlugin che funziona ragionevolmente bene.
NOTA: Se l'installazione di questi plugin non ti funziona, puoi trovare tutti questi metodi nell'oggetto Person.java che viene utilizzato per il test di AppGen. Basta che guardi in extras/appgen/test/dao/org/appfuse/model/Person.java e fai copia e incolla dei metodi da quella classe.

Dopo aver creato questo POJO, devi aggiungere i tag XDoclet per generare il file di mapping di Hibernate. Questo file di mapping viene utilizzato da Hibernate per mappare oggetti → tabelle e proprietà (variabili) → colonne.

Prima di tutto, aggiungi un @hibernate.class tag che dica ad Hibernate a quale tabella si riferisca questo oggetto:


/**
 * @hibernate.class table="person"
 */
public class Person extends BaseObject {

Devi aggiungere anche un mapping per la primary o XDoclet ti vomiterà una serie di errori durante la generazione del file di mapping. Nota che tutti quei tag @hibernate.* devono essere messi all'interno del Javadoc dei getter dei tuoi POJO.


    /**
     @return Returns the id.
     * @hibernate.id column="id" generator-class="increment" unsaved-value="null"
     */

    public Long getId() {
        return this.id;
    }

Io uso generator-class="increment" invece di generator-class="native" in quanto ho riscontrato qualche problema nell'uso di "native" con altri database. Se hai in programma di usare solo MySQL, ti raccomando di usare il valore "native". Questo tutorial usa increment.

Create a new database table from the object using Ant [#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):


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class
        name="org.appfuse.model.Person"
        table="person"
        dynamic-update="false"
        dynamic-insert="false"
    >

        <id
            name="id"
            column="id"
            type="java.lang.Long"
            unsaved-value="null"
        >
            <generator class="increment">
            </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 you'll add additional @hibernate.property tags for the other columns (first_name, last_name):


    /**
     * @hibernate.property column="first_name" length="50"
     */
    public String getFirstName() {
        return this.firstName;
    }

    /**
     * @hibernate.property column="last_name" length="50"
     */
    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 the 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".

Create a new DaoTest to run JUnit tests on your DAO [#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 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 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 AbstractTransactionalDataSourceSpringContextTests 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.


package org.appfuse.dao;

import org.appfuse.model.Person;
import org.springframework.dao.DataAccessException;

public class PersonDaoTest extends BaseDaoTestCase {
    
    private Person person = null;
    private PersonDao dao = null;

    public void setPersonDao(PersonDao dao) {
        this.dao = dao;
    }
}

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:


    public void testGetPerson() throws Exception {
        person = new Person();
        person.setFirstName("Matt");
        person.setLastName("Raible");

        dao.savePerson(person);
        assertNotNull(person.getId());

        person = dao.getPerson(person.getId());
        assertEquals(person.getFirstName()"Matt");
    }

    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);
        }

        assertEquals(person.getLastName()"Last Name Updated");
    }

    public void testAddAndRemovePerson() throws Exception {
        person = new Person();
        person.setFirstName("Bill");
        person.setLastName("Joy");

        dao.savePerson(person);

        assertEquals(person.getFirstName()"Bill");
        assertNotNull(person.getId());

        if (log.isDebugEnabled()) {
            log.debug("removing 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);
        }
    }

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 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:

<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>
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:

I tend to just hard-code test values into Java code - but the .properties file is an option that works great for large objects.
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 = (Personpopulate(person);

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.

Create a new DAO to perform CRUD on the object [#4]

First off, create a PersonDao.java interface in the src/dao/**/dao directory and specify the basic CRUD methods for any implementation classes.


package org.appfuse.dao;

import org.appfuse.model.Person;

public interface PersonDao extends Dao {
    public Person getPerson(Long personId);
    public void savePerson(Person person);
    public void removePerson(Long personId);
}

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 you need to specify a bean named personDao in applicationContext-hibernate.xml. Before you do that, you need to create the PersonDao implementation class.

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 and implement PersonDao. Javadocs eliminated for brevity.


package org.appfuse.dao.hibernate;

import org.appfuse.model.Person;
import org.appfuse.dao.PersonDao;
import org.springframework.orm.ObjectRetrievalFailureException;

public class PersonDaoHibernate extends BaseDaoHibernate implements PersonDao {

    public Person getPerson(Long id) {
        Person person = (PersongetHibernateTemplate().get(Person.class, id);

        if (person == null) {
            throw new ObjectRetrievalFailureException(Person.class, id);
        }

        return person;
    }

    public void savePerson(Person person) {
        getHibernateTemplate().saveOrUpdate(person);
    }

    public void removePerson(Long id) {
        // object must be loaded before it can be deleted
        getHibernateTemplate().delete(getPerson(id));
    }
}

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.


<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> 

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:


<!-- PersonDao: Hibernate implementation --> 
<bean id="personDao" class="org.appfuse.dao.hibernate.PersonDaoHibernate"
    <property name="sessionFactory" ref="sessionFactory"/>
</bean> 

Run the DaoTest [#6]

Save all your edited files and try running ant test-dao -Dtestcase=PersonDao one more time.

Yeah Baby, Yeah: BUILD SUCCESSFUL
Total time: 9 seconds


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.



Go to top   More info...   Attach file...
This particular version was published on 06-Nov-2006 13:52:56 MST by MarcelloTeodori.