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




JSPWiki v2.2.33

[RSS]


Hide Menu

CreateDAO_pt


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


Parte I: Criando novos DAOs e Objetos no AppFuse - Um HowTo para criar Objetos Java (que representam tabelas) e criar classes Java para persistir estes objetos no banco de dados.

Sobre este Tutorial

Este tutorial mostrara a você como criar uma nova tabela no banco de dados, e como criar código java para acessar esta tabela.

Nós criaremos um objeto e então mais algumas classes para persistir (save/retrieve/delete) aquele objeto do banco de dados. Em termos java, chamaremos o objeto de “Plain Old Java Object” (a.k.a. a POJO). Este objeto basicamente representa uma tabela do banco de dados. As outras classes serão:

  • Um Objeto de Acesso a Dados (a.k.a. a DAO), uma Interface e uma implementação Hibernate
  • Uma classe JUnit para testar se nosso DAO está funcionado

AppFuse usa Hibernate para sua camada de persistência. Hibernate é um framework Objeto/Relacional (OR) que nos permite relacionar objetos Java à tabelas no banco de dados. Permitindo muito facilmente efetuar CRUD (Create, Retrieve, Update, Delete) em nossos objetos.

Você também pode usar iBATIS como opção de framework de persistência. Para instalar iBATIS no AppFuse, veja o arquivo README.TXT em extras/ibatis. Se você estiver usando iBATIS, espero que tenha suas razões e que conheça este framework. Espero também que você descubra como adaptar este tutorial para que funcione com iBATIS. ;-)
I will tell you how I do stuff in the Real World in text like this.

Vamos começar criando um novo Objeto, DAO, Test na arquitetura AppFuse.

Tabela de Conteúdo

  • [1] Criar um novo Objeto e adicionar tags XDoclet
  • [2] Criar uma nova tabela no banco de dados a partir do objeto, usando Ant
  • [3] Criar uma nova classe DaoTest para executar testes JUnit no DAO
  • [4] Criar uma nova classe DAO para efetuar CRUD no objeto
  • [5] Configurar o framework Spring para o objeto Pessoa e PessoaDAO
  • [6] Executar o DaoTest

Criar um novo Objeto e Adicionar tags XDoclet [#1]

A primeira coisa que precisamos fazer é criar um objeto a persistir. Vamos criar um simples objeto “Pessoa” (no diretório src/dao/**model) que tem um id, primeiroNome e ultimoNome (como propriedades).


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
    */
}

Usualmente abro um objeto existente (ex.: User.java ou Resume.java) e o salvo como um novo arquivo. Então deleto todos os métodos e propriedades. Isto me dá um básico cabeçalho JavaDoc. Estou certo que poderia editar os Templates Eclipse para fazer isto, mas eu desenvolvo em 3 diferentes máquinas, e isso é justamente mais fácil.

No fragmento de código acima, nós estamos extendendo BaseObject porque ele contem os seguintes métodos úteis: toString(), equals(), hashCode() - os dois últimos são requeridos pelo Hibernate.

Agora que temos este POJO criado, nós precisamos adicionar tags XDoclet para gerar o arquivo de mapeamento Hibernate. Este arquivo de mapeamento é usado pelo Hibernate para mapear objetos => tabelas e propriedades => colunas.

Primeiro de tudo, nós adicionaremos uma tag @hibernate.class que diz ao Hibernate que tabela este objeto se relaciona:


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

Nós também precisamos adicionar um mapeamento de chave primária ou XDoclet irá vomitar quando gerar o arquivo de mapeamento. Note que todos os tags @hibernate.* deverão ser colocados no JavaDocs dos métodos get de seus POJOs.



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

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

I'm using generator-class="increment" instead of generate-class="native" because I found some issues when using "native" on other databases. If you only plan on using MySQL, I recommend you use the "native" value.

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/dao/gen/**/hibernate directory. Here's the contents of Person.hbm.xml (so far):


<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-mapping-2.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 we'll add additional @hibernate.property tags for our other columns (first_name, last_name):


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

    /**
     @return Returns the lastName.
     * @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 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(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/dao/**/dao directory. This class should extend BaseDaoTestCase, which already exists in this package. This parent class is used to load Spring's ApplicationContext (since Spring binds the layers together), and 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 "rb" variable.

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.


package org.appfuse.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.model.Person;


public class PersonDaoTest extends BaseDaoTestCase {
    
    //~ Instance fields ========================================================

    private Person person = null;
    private PersonDao dao = null;

    //~ Methods ================================================================
    protected void setUp() {
        log = LogFactory.getLog(PersonDaoTest.class);
        dao = (PersonDaoctx.getBean("personDao");
    }

    protected void tearDown() {
        dao = null;
    }

    public static void main(String[] args) {
        junit.textui.TestRunner.run(PersonDaoTest.class);
    }
}

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


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

        assertTrue(person.getLastName().equals("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());
        assertNull(dao.getPerson(person.getId()));
    }

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

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

I tend to just hard-code test values into Java code - but the .properties file is an option.
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 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/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.


package org.appfuse.dao;

import org.appfuse.model.Person;

import java.util.List;

public interface PersonDao extends Dao {

    public List getPeople(Person person);

    public Person getPerson(Long personId);

    public void savePerson(Object 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 we need to specify a bean named personDAO in applicationContext-hibernate.xml. Before we do that, we 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.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.appfuse.model.Person;
import org.appfuse.dao.PersonDao;

import java.util.List;

public class PersonDaoHibernate extends BaseDaoHibernate implements PersonDao {

    private Log log = LogFactory.getLog(PersonDaoHibernate.class);

    public List getPeople(Person person) {
        return getHibernateTemplate().find("from Person");
    }

    public Person getPerson(Long id) {
        return (PersongetHibernateTemplate().get(Person.class, id);
    }

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

    public void removePerson(Long id) {
        Object person = getHibernateTemplate().load(Person.class, id);
        getHibernateTemplate().delete(person);
    }
}

You'll notice here that we're doing nothing with the person parameter. This is just a placeholder for now - in the future you may want to filter on it's properties using Hibernate's Query Language (HQL) or using Criteria Queries.

An example using a Criteria Query:


    Example example = Example.create(person)
                             .excludeZeroes()   //exclude zero valued properties
                             .ignoreCase();       //perform case insensitive string comparisons
    try {
        return getSession().createCriteria(Person.class)
                           .add(example)
                           .list();
    catch (Exception e) {
        throw new DAOException(e);
    }
    return new ArrayList();

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.

Configure Spring for the Person object and PersonDao [#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.


<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> 
        <value>org/appfuse/model/UserCookie.hbm.xml</value> 
        <value>org/appfuse/model/UserRole.hbm.xml</value> 
    </list> 
</property> 

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:


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

You could also use autowire="byName" to the <bean> and get rid of the "sessionFactory" property. Personally, I like having the dependencies of my objects documented (in XML).

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


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



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