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 |
Part I: AppFuse에서 iBATIS DAO와 객체 생성하기 - 데이터베이스에서 객체를 지속하기 위해 Java객체(테이블을 표시하는)와 iBATIS DAO 클래스를 생성하기 위한 방법. 이 튜토리얼에 대해이 튜토리얼은 데이터베이스에서 새로운 테이블을 생성하고 이 테이블에 접근하기 위한 자바코드를 생성하는 방법을 보여줄것이다.당신은 데이터베이스로부터 객체를 지속(save/retrieve/delete)하기 위해 객체와 몇가지 클래스를 생성할것이다. 자바쪽에서는 이 객체를 Plain Old Java Object (a.k.a. a POJO)라고 부른다. 이 객체는 기본적으로 데이터베이스 테이블을 표시한다. "다른 클래스"는 다음이 될것이다. AppFuse는 디폴트로 영속성 레이어를 위해 Hibernate를 사용한다. 어쨌든, 당신은 iBATIS를 설치하고 이것을 대안으로 사용할수 있다. 만약 당신이 원한다면 양쪽다 그것들을 사용할수 있다. AppFuse에서 iBATIS를 설치하기 위해, extras/ibatis내 README.txt파일을 보라(또는 이 디렉토리로 이동하고, ant install를 수행하라). 이 튜토리얼의 Hibernate버전은 here이다.. 폰트 규칙(작업중..)
AppFuse의 프로젝트 구조에서 새로운 객체, DAO 그리고 테스트를 생성하여 시작해보자. 목차
새로운 POJO, 테이블 그리고 SQLMap을 생성하기 [#1]해야할 필요가 있는 첫번째 것은 지속하기 위한 객체를 생성하는 것이다. id, firstName 그리고 lastName(프라퍼티로)을 가지는 간단한 "Person"객체(src/dao/**/model 디렉토리내)를 생성하자. 노트: 이 튜토리얼내 자바코드를 복사하는 것은 Firefox에서는 작동하지 않는다. 대안은 코드블럭을 CTRL+Click하고 복사하는 것이다.
이 클래스는 Person클래스에서 구현할 필요가 있는 3개의 추상 메소드(equals(), hashCode() and toString())를 가지는 BaseObject를 확장한다. 첫번째 두개는 Hibernate에 의해 요구된다. 이것을 하는 가장 쉬운 방법은 Commonclipse를 사용하는 것이다. 이 툴을 사용하는 것에 대한 더 많은 정보는 Lee Grey의 사이트에서 볼수 있다. 당신이 사용할수 있는 또 다른 Eclipse플러그인은 Commons4E이다.
새로운 데이터베이스 테이블과 맵핑파일 생성하기 [#2]이 POJO가 생성된 지금, 당신은 POJO가 맵핑할 "person" 데이터베이스 테이블을 생성할 필요가 있다. 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) ); 그리고 나서 "ant setup-db"를 수행한다. 이것은 당신을 위해 person테이블을 생성할 것이다. SQL-대-자바 맵핑파일을 생성하기 위해, src/dao/**/ibatis/sql내 PersonSQL.xml를 생성하라. 이것은 다음을 포함할것이다.
지금 당신은 새로운 SQLMap가 존재하는 것을 iBATIS에 알릴필요가 있을것이다. src/dao/**/ibatis/sql-map-config.xml를 열고 다음을 추가하라. <sqlMap resource="org/appfuse/dao/ibatis/sql/PersonSQL.xml"/> DAO에서 JUnit테스트를 수행하기 위해 새로운 DaoTest 생성하기 [#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.
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:
<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 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:
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 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.
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.
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.
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:
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 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.
|