Creating Mybatis Mapper xmls and usage of MapperFactoryBean, MapperScannerConfig

We are going to use Spring 3x and Mybatis 3x in conjunction here.

Pre-requisite :
Download the Mybatis-Spring bundle : mybatis-spring-1.1.1-bundle and use the libs assorted.
Spring version : 3.1.1
Mybatis version : 3.1.0
Please note the version 1.1.1 for mybatis-spring bundle. There were some issues with 1.1.0 bundle for loading of properties using Spring’s PropertyPlaceHolderConfigurer, but more on that later.

Mybatis

Mybatis is a persistence framework. Mybatis is not an ORM framework and doesn’t map Java objects to database rows. However, it maps methods to SQL statements.

Mybatis vs. Hibernate

I have used both Mybatis and Hibernate in my applications, and both have their pros and cons. However, of late, I have moved more and more towards Mybatis.

IMO, if the object graph is complex, then it is better to use Mybatis and not Hibernate. Hibernate has its own version of lazy loading, but the more associations an object has or the heavier an object is, the more it becomes a performance hit.

In one of our applications which used Hibernate, we finally had to rewrite several queries in order to perform thin loading, or loading only those attributes which are required.

For further details regarding Mybatis, please visit http://en.wikipedia.org/wiki/MyBatis
For Spring-Mybatis, :here

Spring vs Struts for MVC

As regards Spring vs Struts for MVC, again to each his own. Struts 2x is pretty good when it comes to writing less code to do more and I had recently developed an application using Struts 2x. However, most of the transaction management there was programmatic, which needless to say is ugly and error prone. I had to spend lots of time testing out my code.

Now, this last statement is not strictly a Spring MVC advantage or a Struts flaw, because its just an MVC framework and nothing more. However, when we talk about Spring, we get to use the IOC container as well along with its declarative transaction management. Plus, the community support is really good, which invariably helps if you hit a roadblock. One more thing, which I really like about Spring is its view-agnostic (Yes I picked up this word somewhere on the net) It means that it really allows you to custom build any view implementation you like and not just stick to JSPs.(Though Struts 2x has some similar implementations using FreeMarker)

We would be using Eclipse as an IDE to do our development and this is an image of all jars which will be required eventually. Some of them like the commons*.jar and mybatis-ehcache*.jar will have to be downloaded separately.

spring mybatis libs/ jars

Since, by now we have a working Spring MVC application here, we will piggyback on it and add the required configurations. We will revisit our application’s web.xml. (This is just the relevant part, for the entire xml, please refer here.)

01 <context-param>
02 <param-name>contextConfigLocation</param-name>
03 <param-value>
04 /WEB-INF/spring/app-config.xml
05 /WEB-INF/spring/database-config.xml
06 /WEB-INF/spring/mapper-config.xml
07 </param-value>
08 </context-param>
09 <listener>
10 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
11 </listener>

Right, so from here we can see that the ContextLoaderListener will check on

    database-config.xml which will contain the database configuration.
    mapper-config.xml which will point to the individual Mybatis interfaces.

database-config.xml

01 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
02 destroy-method="close">
03 <property name="driverClassName" value="${driver}" />
04 <property name="url" value="${url}" />
05 <property name="username" value="${username}" />
06 <property name="password" value="${password}" />
07 <property name="defaultAutoCommit" value="false" />
08 </bean>
09 <bean id="txManager"
10 class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
11 <property name="dataSource" ref="dataSource" />
12 </bean>
13 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
14 <property name="dataSource" ref="dataSource" />
15 <property name="mapperLocations" value="classpath:com/mybatis/mappers/*.xml" />
16 <property name="configLocation" value="WEB-INF/mybatis-config/mybatis-config.xml" />
17 </bean>

We see 3 beans here :dataSource, txManager and sqlSessionFactory . For dataSource, we will be using dbcp’s BasicDataSource. We would come to the txmanager later.

Now, if you are observant, you would see that the credentials of the datasource are encoded. This is an industry standard, where sensitive information is stored on a keystore or an external property file. Then, the access for this file is controlled by the system administrators on the server. We would see later how, Spring help to retrieve these property values.

For now, let’s concentrate only on the sqlSessionFactory and its attributes.

It has 3 attributes :

    refers to the dataSource,
    mapperLocations which is where we would store our mybatis xml files. Ant style configuration for mapperLocation: if we put it as value=“classpath*:com/mybatis/mappers/*.xml” /> then it will also look into the subpackages recursively
    configLocation where we would store a custom mybatis configuration file to override some important settings.

mapper-config.xml

1 <bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
2 <property name="mapperInterface" value="com.mybatis.dao.BaseMapperInterface" />
3 <property name="sqlSessionFactory" ref="sqlSessionFactory" />
4 </bean>
5 <bean id="employeeMapper" parent="baseMapper">
6 <property name="mapperInterface" value="com.mybatis.dao.EmployeeMapperInterface" />
7 </bean>

2 important concepts explained here:

    We have a BaseMapperInterface which contains a reference to the sqlSessionFactory and this class is simply extended by the rest of the mapper interfaces so that individual interfaces do not have to link in the sqlSessionFactory.
    Presence of a MapperFactoryBean which we will revisit later.

mybatis-config.xml

This is a bare-bones configuration file which we will augment as we learn more about Mybatis.

01 <?xml version="1.0" encoding="UTF-8" ?>
02 <!DOCTYPE configuration
03 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
04 "http://mybatis.org/dtd/mybatis-3-config.dtd">
05 <configuration>
06 <settings>
07 <setting name="cacheEnabled" value="true" />
08 <setting name="lazyLoadingEnabled" value="true" />
09 <setting name="multipleResultSetsEnabled" value="true" />
10 <setting name="useColumnLabel" value="true" />
11 <setting name="useGeneratedKeys" value="false" />
12 <setting name="defaultExecutorType" value="SIMPLE" />
13 <setting name="defaultStatementTimeout" value="100" />
14 <setting name="safeRowBoundsEnabled" value="false" />
15 <setting name="mapUnderscoreToCamelCase" value="false" />
16 <setting name="localCacheScope" value="SESSION" />
17 <setting name="jdbcTypeForNull" value="OTHER" />
18 <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />
19 </settings>
20 </configuration>

So, we have done our configurations. One more small thing of using Spring to decipher the properties for us. We can put this in the app-config.xml which is also listened to by the ContextLoaderListener(check the web.xml earlier on this page)

1 <bean class=<em>"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"</em>>
2 <property name="location">
3 <value>classpath:config.properties</value>
4 </property>
5 </bean>

Interesting Note: we can use our custom PropertyPlaceHolderConfigurer by extending the above mentioned class.We only need to override the following method :

1 public String convertPropertyValue(final String originalValue) {
2 //whatever decoding/decrypting logic u want to put.
3 //U can first encrypt and then encode the property in the property file.
4 }

Right, so our configurational changes have been completed.

Now a typical approach is having the service layer get access to the Mapper interfaces.

So, the interaction would be like Controller(Web layer) accesses the Service Façade which accesses the Mybatis DAO layer/interfaces.

Our sample application would have a login screen for a manager. When the manager successfully logs in, he or she would be able to view his/her employees. On clicking any of the employee’s hyperlink, the manager would get access to the employee’s details which can then be modified.

In step 2, we will be creating our controllers.

This tutorial has been linked in Mybatis wiki : http://code.google.com/p/mybatis

你可能感兴趣的:(FactoryBean)