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




JSPWiki v2.2.33

[RSS]


Hide Menu

CreateDAOiBATIS_ko


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


Part I: AppFuse에서 iBATIS DAO와 객체 생성하기 - 데이터베이스에서 객체를 지속하기 위해 Java객체(테이블을 표시하는)와 iBATIS DAO 클래스를 생성하기 위한 방법.

이 튜토리얼에 대해

이 튜토리얼은 데이터베이스에서 새로운 테이블을 생성하고 이 테이블에 접근하기 위한 자바코드를 생성하는 방법을 보여줄것이다.

당신은 데이터베이스로부터 객체를 지속(save/retrieve/delete)하기 위해 객체와 몇가지 클래스를 생성할것이다. 자바쪽에서는 이 객체를 Plain Old Java Object (a.k.a. a POJO)라고 부른다. 이 객체는 기본적으로 데이터베이스 테이블을 표시한다. "다른 클래스"는 다음이 될것이다.

  • 데이터 접근 객체 (a.k.a. a DAO), Interface 그리고 iBATIS구현물
  • DAO를 테스트하기 위한 JUnit 클래스

AppFuse는 디폴트로 영속성 레이어를 위해 Hibernate를 사용한다. 어쨌든, 당신은 iBATIS를 설치하고 이것을 대안으로 사용할수 있다. 만약 당신이 원한다면 양쪽다 그것들을 사용할수 있다. AppFuse에서 iBATIS를 설치하기 위해, extras/ibatis내 README.txt파일을 보라(또는 이 디렉토리로 이동하고, ant install를 수행하라). 이 튜토리얼의 Hibernate버전은 here이다..

폰트 규칙(작업중..)

명령창에서 수행되는 경향이 있는 문자열은 다음과 같이 보일것이다: ant test-all.
소스 트리에 존재하는 파일, 디렉토리 그리고 패키지에 대한 참조: build.xml.
그리고 "실제 세상"에서 채우는 방법을 위한 제안은 파란색의 이탤릭체이다..

AppFuse의 프로젝트 구조에서 새로운 객체, DAO 그리고 테스트를 생성하여 시작해보자.

목차

  • [1] 새로운 Person POJO생성하기.
  • [2] 새로운 데이터베이스 테이블과 맵핑 파일 생성하기
  • [3] DAO에서 JUnit테스트를 수행하기 위해 새로운 DaoTest 생성하기
  • [4] 객체에서 CRUD를 수행하기 위해 새로운 DAO 생성하기
  • [5] PersonDao를 위해 bean정의 생성하기
  • [6] DaoTest 수행하기

새로운 POJO, 테이블 그리고 SQLMap을 생성하기 [#1]

해야할 필요가 있는 첫번째 것은 지속하기 위한 객체를 생성하는 것이다. id, firstName 그리고 lastName(프라퍼티로)을 가지는 간단한 "Person"객체(src/dao/**/model 디렉토리내)를 생성하자.

노트: 이 튜토리얼내 자바코드를 복사하는 것은 Firefox에서는 작동하지 않는다. 대안은 코드블럭을 CTRL+Click하고 복사하는 것이다.


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

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.

If you're using IntelliJ IDEA, you can generate equals() and hashCode(), but not toString(). There is a ToStringPlugin that works reasonably well.
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.

Create a new database table and mapping file [#2]

Now that you have this POJO created, you need to create a "person" database table that your POJO will map to. Add the following to metadata/sql/mysql-create-tables.sql:
CREATE TABLE person (
    person_id int(8) auto_increment,
    first_name varchar(50) NOT NULL,
    last_name varchar(50) NOT NULL,
    PRIMARY KEY (person_id)
);

Then run "ant setup-db". This will create the person table for you. To create the SQL-to-Java mapping file, create PersonSQL.xml in src/dao/**/ibatis/sql. It should contain the following XML:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" 
    "http://www.ibatis.com/dtd/sql-map-2.dtd">

<sqlMap namespace="PersonSQL">
    <typeAlias alias="person" type="org.appfuse.model.Person"/>

    <parameterMap id="addParam" class="person">
        <parameter property="firstName" jdbcType="VARCHAR" javaType="java.lang.String"/>
        <parameter property="lastName" jdbcType="VARCHAR" javaType="java.lang.String"/>
    </parameterMap>

    <parameterMap id="updateParam" class="person">
        <parameter property="personId" jdbcType="INTEGER" javaType="java.lang.Long"/>
        <parameter property="firstName" jdbcType="VARCHAR" javaType="java.lang.String"/>
        <parameter property="lastName" jdbcType="VARCHAR" javaType="java.lang.String"/>
    </parameterMap>

    <resultMap id="personResult" class="person">
        <result property="personId" column="person_id"/>
        <result property="firstName" column="first_name"/>
        <result property="lastName" column="last_name"/>
    </resultMap>

    <select id="getPersons" resultMap="personResult">
    <![CDATA[
        select * from person
    ]]>
    </select>

    <select id="getPerson" resultMap="personResult">
    <![CDATA[
        select * from person where person_id = #value#
    ]]>
    </select>

    <insert id="addPerson" parameterMap="addParam">
        <selectKey resultClass="java.lang.Long" keyProperty="personId">
      SELECT LAST_INSERT_ID() AS personId
    </selectKey>
        <![CDATA[
            insert into person (first_name,last_name)
            values ?,?,? )
        ]]>
    </insert>

    <update id="updatePerson" parameterMap="updateParam">
    <![CDATA[
        update person set
                   first_name = ?,
                   last_name = ?
        where person_id = ?
    ]]>
    </update>

    <delete id="deletePerson">
    <![CDATA[
        delete from person where person_id = #value#
    ]]>
    </delete>
</sqlMap>

NOTE: Since iBATIS doesn't support JDBC 3.0's getGeneratedKeys(), you need to use a <selectKey> element that's specific to your database. In this example, the <selectKey> in <insert id="addPerson"> is MySQL's syntax. Of course, if you don't care about fetching the primary key after an object is inserted, you won't need this.

Now you'll need to notify iBATIS that a new SQLMap exists. Open src/dao/**/ibatis/sql-map-config.xml and add the following:

<sqlMap resource="org/appfuse/dao/ibatis/sql/PersonSQL.xml"/>

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 PersonDaoiBatis.java is the iBATIS 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-ibatis.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 PersonDaoiBatis class that implements the methods in PersonDao and uses iBATIS to get/save/delete the Person object. To do this, create a new class in src/dao/**/dao/ibatis and name it PersonDaoiBatis.java. It should extend BaseDaoiBatis and implement PersonDao.


package org.appfuse.dao.ibatis;

import java.util.List;

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

import org.springframework.orm.ObjectRetrievalFailureException;

public class PersonDaoiBatis extends BaseDaoiBATIS implements PersonDao {

    public Person getPerson(Long personId) {
        Person person = (PersongetSqlMapClientTemplate().queryForObject("getPerson", personId);

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

        return person;
    }
  
    public void savePerson(final Person person) {
        Long personId = person.getPersonId();
        // check for new record
        if (personId == null) {
            personId = (LonggetSqlMapClientTemplate().insert("addPerson", person);
        else {
            getSqlMapClientTemplate().update("updatePerson", person);
        }
        ifpersonId == null ) {
            throw new ObjectRetrievalFailureException(Person.class, personId);
        }
    }

    public void removePerson(Long personId) {
        getSqlMapClientTemplate().update("deletePerson", personId);
    }
}

Now, if you try to run ant test-dao -Dtestcase=PersonDao, you will get the same error. Yo need to configure Spring so it knows that PersonDaoiBatis is the implementation of PersonDao.

Create a bean definition for the PersonDao [#5]

In order to bind PersonDaoiBatis to the PersonDao interface, you need to register a "personDao" bean definition in src/dao/**/dao/ibatis/applicationContext-ibatis.xml. Open this file and add the following at the bottom:


<!-- PersonDao: iBATIS implementation --> 
<bean id="personDao" class="org.appfuse.dao.ibatis.PersonDaoiBatis">
    <property name="dataSource" ref="dataSource"/>
    <property name="sqlMapClient" ref="sqlMapClient"/>
</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:54 MST by DongGukLee.