Mapping Files

Let's begin with a description of the reference configuration file. Unlike stand-alone iBATIS applications, you normally only include references to the concrete sqlMap files.

Listing 10-1 shows a sample reference configuration file.

Listing 10-1: SqlMapConfig.XML Reference Configuration File

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

As you can see in Listing 10-2, the configuration file references a single sqlMap file, Test.xml, which in turn declares the domain object type.

Listing 10-2: sqlMap File for Test Class

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

At this point, we have the basic infrastructure of the application ready. The missing piece of the puzzle is the Spring context file that links all the configuration files together (see Listing 10-3).

Listing 10-3: Spring applicationContext.xml File

image from book
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" ¿ "http://www.springframework.org/dtd/spring-beans.dtd">      <beans>          <!-- SqlMap setup for iBATIS Database Layer -->     <bean           >         <property name="configLocation">             <value>sqlMapConfig.xml</value>         </property>     </bean>      </beans>
image from book

Listing 10-3 shows you how to instruct Spring to create an instance of the sqlMapClient bean, which loads the sqlMapConfig.xml file. We now have a configured sqlMapClient bean that can be used in the DAO implementations. All we need to do is define the DAO interfaces, create the implementation, and create the dataSource bean; but before we can do that, we must take a more detailed look at the map files.

In Table 10-1, we review the files we have and how we are going to structure them.

Table 10-1: Locations of the Configuration Files

File

Source Location

Build/Run Location

sqlMapClient.xml

src/ibatis

build

Test.xml

src/ibatis

build

applicationContext

src/conf

build

The build script, build.xml, takes care of building the application and makes sure that the configuration files are copied from their source location to the appropriate destination to run the application. Before we can move ahead and complete the configuration files and make the application work, we need to take a closer look at the sqlMap files.

The location of the files is specific to the application type you are developing. It is important to realize that the configuration files are resources and as such, they are handled by ResourceLoaders; usually the default ResourceLoader. Refer to Chapter 5 for more information on resources.

SqlMap Files

sqlMap defines types, result maps, and database statements. Even though you can use a single file, it is a good idea to create a separate sqlMap file for each domain object. If you follow this simple rule, you will keep the sqlMap files easy to read, and as the number of domain objects grows, the project will remain easy to manage.

In Listing 10-4, we create a simple database with a single table to demonstrate the iBATIS functionality.

Listing 10-4: SQL Create Script

image from book
create table Test (     TestId serial not null,     Name varchar(50) not null,      RunDate timestamp not null,          constraint PK_TestId primary key (TestId) );      insert into Test (Name, RunDate) values 
image from book

Next, we create a domain object to map in the sqlMap file. The domain object (see Listing 10-5) has the same class name as the sqlMap file, Test, and it is going to have the same properties as the Test table columns.

Listing 10-5: Test Domain Object

image from book
package com.apress.prospring.ch12.domain;      import java.util.Date;      public class Test {          private int testId;     private String name;     private Date runDate;          // Operations          public String toString() {         StringBuffer result = new StringBuffer(50);         result.append("Test { testId: ");         result.append(testId);         result.append(", name: ");         result.append(name);         result.append(", runDate: ");         result.append(runDate);         result.append(" }");         return result.toString();     }          // Getters and setters          public String getName() {         return name;     }          public void setName(String name) {         this.name = name;     }          public Date getRunDate() {         return runDate;     }          public void setRunDate(Date runDate) {         this.runDate = runDate;     }          public int getTestId() {         return testId;     }          public void setTestId(int testId) {         this.testId = testId;     } }
image from book

The domain object has three properties, testId, name, and runDate. We need to tell iBATIS how to interpret the data that will be selected from the database. To do this, we create a resultMap element that tells iBATIS what object to instantiate and what properties to set (see Listing 10-6).

Listing 10-6: sqlMap File for the Test Domain Object

image from book
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" ¿ "http://www.ibatis.com/dtd/sql-map-2.dtd">   <sqlMap>          <typeAlias type="com.apress.prospring.ch12.domain.Test" alias="test"/>          <resultMap bold">test" >         <result property="testId" column="TestId"/>         <result property="name" column="Name"/>         <result property="runDate" column="RunDate"/>     </resultMap>          </sqlMap>
image from book

Listing 10-6 actually shows how to create a typeAlias that tells iBATIS that Test actually means com.apress.prospring.ch12.domain.Test; this is a merely a convenience feature to save you typing. Table 10-2 lists all predefined aliases and their corresponding Java types.

Table 10-2: Predefined iBATIS Type Aliases

Alias

Java Type

Details

boolean

java.lang.Boolean

Use #value# to access the object's primitive boolean property.

byte

java.lang.Byte

Use #value# to access the object's primitive byte property.

short

java.lang.Short

Use #value# to access the object's primitive short property.

int

java.lang.Integer

Use #value# to access the object's primitive int property.

long

java.lang.Long

Use #value# to access the object's primitive long property.

float

java.lang.Float

Use #value# to access the object's primitive float property.

double

java.lang.Double

Use #value# to access the object's primitive double property.

string

java.lang.String

Use #value# to access the object's value.

date

java.util.Date

Use #value# to access the object's value.

decimal

java.math.BigDecimal

Use #value# to access the object's value.

map

java.util.Map

Use #key# to get or set the item in the Map.

Next, we define a resultMap with an ID of result. When a resultMap with the name result is used, iBATIS instantiates the Test object and sets its properties with the values in the appropriate columns (see Listing 10-7).

Listing 10-7: sqlMap File for the Select Statement of the Test Domain Object

image from book
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" ¿ "http://www.ibatis.com/dtd/sql-map-2.dtd">   <sqlMap>          <typeAlias type="com.apress.prospring.ch12.domain.Test" alias="test"/>          <resultMap  bold">result">         <result property="testId" column="TestId"/>         <result property="name" column="Name"/>         <result property="runDate" column="RunDate"/>     </resultMap>              <select  resultMap="result">         select * from Test     </select> </sqlMap>
image from book

Don't worry if you don't understand what a select node does or what to use it for, we will discuss this further in the "Selecting Data" section later in this chapter.

Configuring iBATIS and Spring

Finally, we can define the TestDao interface and its iBATIS implementation and then add the familiar dataSource bean.

Note 

If you cannot remember how to configure dataSource beans, go back to Chapter 8 where we discussed different DataSources you can use in a Spring application.

In Listing 10-8, we begin with TestDao, a DAO interface, and the SqlMapClientTestDao implementation.

Listing 10-8: TestDao Interface

image from book
package com.apress.prospring.ch12.data;      import java.util.List;      import com.apress.prospring.ch12.domain.Test;      public interface TestDao {     public List getAll();     public List getByNameAndRunDate(String name, Date runDate);     public void save(Test test);     public void delete(int testId);     public Test getById(int testId);     public List getByNameAndRunDate(String name, Date runDate);     public void updateName(int testId, String name); }
image from book

We now proceed to implement this interface (see Listing 10-9). We use a convenience Spring superclass, SqlMapClientDaoSupport. Just like JdbcDaoSupport, this class already has a property for a dataSource and provides getSqlMapClientTemplate(), which allow us to call iBATIS methods.

Listing 10-9: TestDao iBATIS Implementation

image from book
package com.apress.prospring.ch12.data;      import java.util.List;      import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;      import com.apress.prospring.ch12.domain.Test;      public class SqlMapClientTestDao      extends SqlMapClientDaoSupport      implements TestDao {          // TestDao methods are implemented as stubs }
image from book

In Listing 10-10, we finish the applicationContext.xml file to link the beans together.

Listing 10-10: Spring applicationContext.xml File

image from book
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" ¿ "http://www.springframework.org/dtd/spring-beans.dtd">      <beans>     <!-- Data source bean -->     <bean            destroy-method="close">         <property name="driverClassName">             <value>org.postgresql.Driver</value>         </property>         <property name="url">             <value>jdbc:postgresql://localhost/prospring</value></property>         <property name="username"><value>janm</value></property>         <property name="password"><value>****</value></property>     </bean>           <!-- SqlMap setup for iBATIS Database Layer -->     <bean           >         <property name="configLocation">             <value>sqlMapConfig.xml</value>         </property>     </bean>          <bean           >         <property name="dataSource"><ref local="dataSource"/></property>         <property name="sqlMapClient"><ref local="sqlMapClient"/></property>     </bean>      </beans>
image from book

We're almost there, now. We have a full Spring application context file with the dataSource, sqlMapClient, and testDao beans. We can now create a Main class (see Listing 10-11) that creates the application context from the context file on the classpath and selects and prints the data.

Listing 10-11: The Sample Application's Main Class

image from book
package com.apress.prospring.ch12;      import java.util.Iterator; import java.util.List;      import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;      import com.apress.prospring.ch12.data.TestDao; import com.apress.prospring.ch12.domain.Test;          public class Main {          private ApplicationContext context;          private void run() {         System.out.println("Initializing application");         context = new ClassPathXmlApplicationContext("applicationContext.xml");                  System.out.println("Getting testDao");         TestDao testDao = (TestDao)context.getBean("testDao");                  System.out.println("Done");     }          public static void main(String[] args) {         new Main().run();     }      }
image from book

The framework for the application is now ready. Once executed, the Spring application context is loaded and all beans are successfully configured. However, we cannot see any data just yet, so let's move on to the next section.



Pro Spring
Pro Spring
ISBN: 1590594614
EAN: 2147483647
Year: 2006
Pages: 189

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net