`
zhaohaolin
  • 浏览: 986881 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

MyBatis3整合Spring3、SpringMVC3

阅读更多

开发环境:

System:Windows

WebBrowser:IE6+、Firefox3+

JavaEE Server:tomcat5.0.2.8、tomcat6

IDE:eclipse、MyEclipse 8

Database:MySQL

开发依赖库:

JavaEE5、Spring 3.0.5、Mybatis 3.0.4、myBatis-spring-1.0、junit4.8.2

Email:hoojo_@126.com

Blog:http://blog.csdn.net/IBM_hoojo

http://hoojo.cnblogs.com/

百度文库:http://wenku.baidu.com/view/34559702a6c30c2259019e4e.html

1、 首先新建一个WebProject 命名为MyBatisForSpring,新建项目时,使用JavaEE5的lib库。然后手动添加需要的jar包,所需jar包如下:

clip_image002

2、 添加spring的监听及springMVC的核心Servlet,web.xml内容,内容如下:

<!-- 加载Spring容器配置 -->
<
listener
>
    <
listener-class
>
org.springframework.web.context.ContextLoaderListener</
listener-class
>
</
listener
>
 
<!-- 设置Spring容器加载配置文件路径 -->
<
context-param
>
    <
param-name
>
contextConfigLocation</
param-name
>
    <
param-value
>
classpath*:applicationContext-*.xml</
param-value
>
</
context-param
>
 
<!-- 配置Spring核心控制器 -->
<
servlet
>
    <
servlet-name
>
dispatcher</
servlet-name
>
    <
servlet-class
>
org.springframework.web.servlet.DispatcherServlet</
servlet-class
>
    <
init-param
>
        <
param-name
>
contextConfigLocation</
param-name
>
        <
param-value
>
/WEB-INF/dispatcher.xml</
param-value
>
    </
init-param
>
    <
load-on-startup
>
1</
load-on-startup
>
</
servlet
>
 
<
servlet-mapping
>
    <
servlet-name
>
dispatcher</
servlet-name
>
    <
url-pattern
>
*.do</
url-pattern
>
</
servlet-mapping
>
 
<!-- 解决工程编码过滤器 -->
<
filter
>
    <
filter-name
>
characterEncodingFilter</
filter-name
>
    <
filter-class
>
org.springframework.web.filter.CharacterEncodingFilter</
filter-class
>
    <
init-param
>
        <
param-name
>
encoding</
param-name
>
        <
param-value
>
UTF-8</
param-value
>
    </
init-param
>
</
filter
>
 
<
filter-mapping
>
    <
filter-name
>
characterEncodingFilter</
filter-name
>
    <
url-pattern
>
/*</
url-pattern
>
</
filter-mapping
>

3、 在WEB-INF目录中添加dispatcher.xml,内容如下:

<?
xml
 version
="1.0"
 encoding
="UTF-8"
?>
<
beans
 xmlns
="http://www.springframework.org/schema/beans"
    xmlns:context
="http://www.springframework.org/schema/context"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans 
>
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"
    <!-- 注解探测器 -->
    <
context:component-scan
 base-package
="com.hoo"
/>
    
    <!--  annotation默认的方法映射适配器 -->
    <
bean
 id
="handlerMapping"
 class
="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"
 />
 
    <
bean
 id
="handlerAdapter"
 class
="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
 />
</
beans
>

4、 在src目录下添加applicationContext-common.xml,内容如下:

<?
xml
 version
="1.0"
 encoding
="UTF-8"
?>
<
beans
 xmlns
="http://www.springframework.org/schema/beans"
    xmlns:aop
="http://www.springframework.org/schema/aop"
 
    xmlns:tx
="http://www.springframework.org/schema/tx"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans 
>
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "
    
    <!-- 配置DataSource数据源 -->
    <
bean
 id
="dataSource"
 class
="org.springframework.jdbc.datasource.DriverManagerDataSource"
>
        <
property
 name
="driverClassName"
 value
="com.mysql.jdbc.Driver"
/>
        <
property
 name
="url"
 value
="jdbc:mysql://10.0.0.131:3306/ash2"
/>
        <
property
 name
="username"
 value
="dev"
/>
        <
property
 name
="password"
 value
="dev"
/>
    </
bean
>
    
    <!-- 配置SqlSessionFactoryBean -->
    <
bean
 id
="sqlSessionFactory"
 class
="org.mybatis.spring.SqlSessionFactoryBean"
>
        <
property
 name
="dataSource"
 ref
="dataSource"
/>
        <
property
 name
="configLocation"
 value
="classpath:mybatis.xml"
/>
        <!-- mapper和resultmap配置路径 -->
        <
property
 name
="mapperLocations"
>
            <
list
>
                <!-- 表示在com.hoo.resultmap包或以下所有目录中,以-resultmap.xml结尾所有文件 -->
                <
value
>
classpath:com/hoo/resultmap/**/*-resultmap.xml</
value
>
                <
value
>
classpath:com/hoo/entity/*-resultmap.xml</
value
>
                <
value
>
classpath:com/hoo/mapper/**/*-mapper.xml</
value
>
            </
list
>
        </
property
>
    </
bean
>
    
    <!-- 单独配置一个Mapper; 这种模式就是得给每个mapper接口配置一个bean -->
    <!-- 
    <bean id="accountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
        <property name="mapperInterface" value="com.hoo.mapper.AccountMapper" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
    </bean> 
    
    <bean id="companyMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
        <property name="mapperInterface" value="com.hoo.mapper.CompanyMapper" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
    </bean>
     -->
 
    
    <!-- 通过扫描的模式,扫描目录在com/hoo/mapper目录下,所有的mapper都继承SqlMapper接口的接口, 这样一个bean就可以了 -->
    <
bean
 class
="org.mybatis.spring.mapper.MapperScannerConfigurer"
>
        <
property
 name
="basePackage"
 value
="com.hoo.mapper"
/>
        <
property
 name
="markerInterface"
 value
="com.hoo.mapper.SqlMapper"
/>
    </
bean
>
</
beans
>

上面的配置最先配置的是DataSource,这里采用的是jdbc的DataSource;

然后是SqlSessionFactoryBean,这个配置比较关键。SqlSessionFactoryBean需要注入DataSource 数据源,其次还要设置configLocation也就是mybatis的xml配置文件路径,完成一些关于mybatis的配置,如settings、 mappers、plugin等;

如果使用mapperCannerConfigurer模式,需要设置扫描根路径也就是你的mybatis的mapper接口所在包路径;凡是 markerInterface这个接口的子接口都参与到这个扫描,也就是说所有的mapper接口继承这个SqlMapper。

如果你不使用自己的transaction事务,就使用MapperScannerConfigurer来完成SqlSession的打开、关闭和 事务的回滚操作。在此期间,出现数据库操作的如何异常都会被转换成DataAccessException,这个异常是一个抽象的类,继承 RuntimeException;

5、 SqlMapper内容如下:

package
 com.hoo.mapper;
 
/**
 * <b>function:</b>所有的Mapper继承这个接口
 * @author hoojo
 * @createDate 2011-4-12 下午04:00:31
 * @file SqlMapper.java
 * @package com.hoo.mapper
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public
 interface
 SqlMapper {
 
}

6、 实体类和ResultMap.xml

package
 com.hoo.entity;
 
import
 java.io.Serializable;
import
 javax.persistence.Entity;
 
@Entity
public
 class
 Account implements
 Serializable {
 
    private
 static
 final
 long
 serialVersionUID = -7970848646314840509L;
 
    private
 Integer accountId;
    private
 Integer status;
    private
 String username;
    private
 String password;
    private
 String salt;
    private
 String email;
    private
 Integer roleId;
    
    //getter、setter
 
    @Override
    public
 String toString() {
        return
 this
.accountId + "#"
 + this
.status + "#"
 + this
.username +  "#"
 + 
            this
.password +  "#"
 + this
.email +  "#"
 + this
.salt + "#"
 + this
.roleId;
    }
}

account-resultmap.xml

<?
xml
 version
="1.0"
 encoding
="UTF-8"
?>
<!
DOCTYPE
 mapper
 PUBLIC
 "-//mybatis.org//DTD Mapper 3.0//EN"
 
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
>
<
mapper
 namespace
="accountMap"
>
    <
resultMap
 type
="com.hoo.entity.Account"
 id
="accountResultMap"
>
        <
id
 property
="accountId"
 column
="account_id"
/>
        <
result
 property
="username"
 column
="username"
/>
        <
result
 property
="password"
 column
="password"
/>
        <
result
 property
="status"
 column
="status"
/>
    </
resultMap
>
</
mapper
>

7、 在src目录中添加applicationContext-beans.xml内容如下:

<?
xml
 version
="1.0"
 encoding
="UTF-8"
?>
<
beans
 xmlns
="http://www.springframework.org/schema/beans"
    xmlns:context
="http://www.springframework.org/schema/context"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans 
>
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"
    <!-- 注解探测器 , 在JUnit测试的时候需要-->
    <
context:component-scan
 base-package
="com.hoo"
/>
    
</
beans
>

这里配置bean对象,一些不能用annotation注解的对象就可以配置在这里

8、 在src目录中添加mybatis.xml,内容如下:

<?
xml
 version
="1.0"
 encoding
="UTF-8"
 ?>
<!
DOCTYPE
 configuration
 PUBLIC
 "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd"
>
<
configuration
>
    <!-- 别名 -->
    <
typeAliases
>
        <
typeAlias
 type
="com.hoo.entity.Account"
 alias
="account"
/>
    </
typeAliases
>
</
configuration
>

在这个文件放置一些全局性的配置,如handler、objectFactory、plugin、以及mappers的映射路径(由于在 applicationContext-common中的SqlSessionFactoryBean有配置mapper的location,这里就不需 要配置)等

9、 AccountMapper接口,内容如下:

package
 com.hoo.mapper;
 
import
 java.util.List;
import
 org.apache.ibatis.annotations.Select;
import
 com.hoo.entity.Account;
 
/**
 * <b>function:</b>继承SqlMapper,MyBatis数据操作接口;此接口无需实现类
 * @author hoojo
 * @createDate 2010-12-21 下午05:21:20
 * @file AccountMapper.java
 * @package com.hoo.mapper
 * @project MyBatis
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public
 interface
 AccountMapper extends
 SqlMapper {
    
    public
 List<Account> getAllAccount();
    
    public
 Account getAccount();
    
    public
 Account getAccountById(String id);
    
    public
 Account getAccountByNames(String spring);
    
    @Select("select * from account where username = #{name}"
)
    public
 Account getAccountByName(String name);
    
    public
 void
 addAccount(Account account);
    
    public
 void
 editAccount(Account account);
    
    public
 void
 removeAccount(int
 id);
}

这个接口我们不需要实现,由mybatis帮助我们实现,我们通过mapper文件配置sql语句即可完成接口的实现。然后这个接口需要继承 SqlMapper接口,不然在其他地方就不能从Spring容器中拿到这个mapper接口,也就是说当我们注入这个接口的时候将会失败。

当然,你不继承这个接口也可以。那就是你需要给买个mapper配置一个bean。配置方法如下:

<
bean
 id
="accountMapper"
 class
="org.mybatis.spring.mapper.MapperFactoryBean"
>
 
    <
property
 name
="mapperInterface"
 value
="com.hoo.mapper.AccountMapper"
 />
    <
property
 name
="sqlSessionFactory"
 ref
="sqlSessionFactory"
 />
 
</
bean
>

这里的MapperFactoryBean可以帮助我们完成Session的打开、关闭等操作

10、 在com.hoo.mapper也就是在AccountMapper接口的同一个包下,添加account-mapper.xml,内容如下:

<?
xml
 version
="1.0"
 encoding
="UTF-8"
?>
<!
DOCTYPE
 mapper
 PUBLIC
 "-//mybatis.org//DTD Mapper 3.0//EN"
 
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
>
<!-- namespace和定义的Mapper接口对应,并实现其中的方法 -->
<
mapper
 namespace
="com.hoo.mapper.AccountMapper"
>
    <!-- id和mapper接口中的方法名对应,resultType使用mybatis.xml中的别名 -->
    <
select
 id
="getAccount"
 resultType
="account"
>
        <!
[CDATA[
            select * from account limit 1
        ]]>
    </
select
>
    
    <
select
 id
="getAllAccount"
 resultType
="list"
 resultMap
="accountResultMap"
>
        <!
[CDATA[
            select * from account
        ]]>
    </
select
>
    
    <!-- accountResultMap是account-resultmap.xml中定义的resultmap -->
    <
select
 id
="getAccountById"
 parameterType
="string"
 resultType
="com.hoo.entity.Account"
 resultMap
="accountResultMap"
>
        <!
[CDATA[
            select * from account where account_id = #{id}
        ]]>
    </
select
>
    
    <!-- accountMap.accountResultMap是account-resultmap.xml中定义的resultmap,通过namespace.id找到 -->
    <
select
 id
="getAccountByNames"
 parameterType
="string"
 resultMap
="accountMap.accountResultMap"
>
        <!
[CDATA[
            select * from account where username = #{name}
        ]]>
    </
select
>
    
    <
sql
 id
="user_name_pwd"
>
        username, password
    </
sql
>
    
    <!-- 自动生成id策略 -->
    <
insert
 id
="addAccount"
 useGeneratedKeys
="true"
 keyProperty
="account_id"
 parameterType
="account"
>
        insert into account(account_id, status, username, password)
        values(#{accountId}, #{status}, #{username}, #{password})
    </
insert
>
    
    <!-- 根据selectKey语句生成主键 -->
    <
insert
 id
="addAccount4Key"
 parameterType
="account"
>
        <
selectKey
 keyProperty
="account_id"
 order
="BEFORE"
 resultType
="int"
>
            select cast(random() * 10000 as Integer) a from #Tab
        </
selectKey
>
        insert into account(account_id, status, username, password)
        values(#{accountId}, #{status}, #{username}, #{password})
    </
insert
>
    
    <
update
 id
="editAccount"
 parameterType
="account"
>
        update account set
        status = #{status},
        username = #{username},
        password = #{password}
        where account_id = #{accountId}
    </
update
>
    
    <
delete
 id
="removeAccount"
 parameterType
="int"
>
        delete from account where account_id = #{id}
    </
delete
>
</
mapper
>

上面的namespace和定义接口类路径对应,所有的sql语句,如select、insert、delete、update的id和方法名称对 应。关于更多MyBatis内容的讲解,这里就不赘述的。这里只完成整合!如果你不懂可以去阅读其他关于MyBatis的资料。

11、 为了测试发布,这里使用junit和spring官方提供的spring-test.jar,完成spring框架整合的测试,代码如下:

package
 com.hoo.mapper;
 
import
 java.util.List;
import
 javax.inject.Inject;
import
 org.springframework.test.context.ContextConfiguration;
import
 org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
import
 com.hoo.entity.Account;
 
/**
 * <b>function:</b> AccountMapper JUnit测试类
 * @author hoojo
 * @createDate 2011-4-12 下午04:21:50
 * @file AccountMapperTest.java
 * @package com.hoo.mapper
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
 
@ContextConfiguration("classpath:applicationContext-*.xml"
)
public
 class
 AccountMapperTest extends
 AbstractJUnit38SpringContextTests {
    
    @Inject
    //@Named("accountMapper")
    private
 AccountMapper mapper;
    
    public
 void
 testGetAccount() {
        System.out.println(mapper.getAccount());
    }
    
    public
 void
 testGetAccountById() {
        System.out.println(mapper.getAccountById("28"
));
    }
    
    public
 void
 testGetAccountByName() {
        System.out.println(mapper.getAccountByName("user"
));
    }
    
    public
 void
 testGetAccountByNames() {
        System.out.println(mapper.getAccountByNames("user"
));
    }
    
    public
 void
 testAdd() {
        Account account = new
 Account();
        account.setEmail("temp@155.com"
);
        account.setPassword("abc"
);
        account.setRoleId(1);
        account.setSalt("ss"
);
        account.setStatus(0);
        account.setUsername("Jack"
);
        mapper.addAccount(account);
    }
    
    public
 void
 testEditAccount() {
        Account acc = mapper.getAccountByNames("Jack"
);
        System.out.println(acc);
        acc.setUsername("Zhangsan"
);
        acc.setPassword("123123"
);
        mapper.editAccount(acc);
        System.out.println(mapper.getAccountById(acc.getAccountId() + ""
));
    }
    
    public
 void
 testRemoveAccount() {
        Account acc = mapper.getAccountByNames("Jack"
);
        mapper.removeAccount(acc.getAccountId());
        System.out.println(mapper.getAccountByNames("Jack"
));
    }
    
    public
 void
 testAccountList() {
        List<Account> acc = mapper.getAllAccount();
        System.out.println(acc.size());
        System.out.println(acc);
    }
}

这里的注入并没有使用@Autowired、@Resource、@Qualifier注入,而是使用@Inject、@Named注入方 式,Inject注入是JSR330的标准注入方式;而不局限于某个产品,使用于多个产品的使用,推荐使用这种方式;运行后,没有发现问题,就可以继续后 续的编码工作了。

12、 定义AccountDao接口及实现代码,代码如下:

package
 com.hoo.dao;
 
import
 java.util.List;
import
 org.springframework.dao.DataAccessException;
 
/**
 * <b>function:</b> Account数据库操作dao接口
 * @author hoojo
 * @createDate 2011-4-13 上午10:21:38
 * @file AccountDao.java
 * @package com.hoo.dao
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public
 interface
 AccountDao<T> {
    
    /**
     * <b>function:</b> 添加Account对象信息
     * @author hoojo
     * @createDate 2011-4-13 上午11:50:05
     * @param entity Account
     * @return boolean 是否成功
     * @throws DataAccessException
     */
    public
 boolean
 addAccount(T entity) throws
 DataAccessException;
    
    /**
     * <b>function:</b> 根据id对到Account信息
     * @author hoojo
     * @createDate 2011-4-13 上午11:50:45
     * @param id 编号id
     * @return Account
     * @throws DataAccessException
     */
    public
 T getAccount(Integer id) throws
 DataAccessException;
    
    /**
     * <b>function:</b> 查询所有Account信息
     * @author hoojo
     * @createDate 2011-4-13 上午11:51:45
     * @param id 编号id
     * @return Account
     * @throws DataAccessException
     */
    public
 List<T> getList() throws
 DataAccessException;
}

接口实现

package
 com.hoo.dao.impl;
 
import
 java.util.List;
import
 javax.inject.Inject;
import
 org.springframework.dao.DataAccessException;
import
 org.springframework.stereotype.Repository;
import
 com.hoo.dao.AccountDao;
import
 com.hoo.entity.Account;
import
 com.hoo.mapper.AccountMapper;
 
/**
 * <b>function:</b> Account数据库操作dao
 * @author hoojo
 * @createDate 2011-4-13 上午10:25:02
 * @file AccountDaoImpl.java
 * @package com.hoo.dao.impl
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@SuppressWarnings("unchecked"
)
@Repository
public
 class
 AccountDaoImpl<T extends
 Account> implements
 AccountDao<T> {
    
    @Inject
    private
 AccountMapper mapper;
    
    public
 boolean
 addAccount(T entity) throws
 DataAccessException {
        boolean
 flag = false;
        try
 {
            mapper.addAccount(entity);
            flag = true;
        } catch
 (DataAccessException e) {
            flag = false;
            throw
 e;
        }
        return
 flag;
    }
 
    public
 T getAccount(Integer id) throws
 DataAccessException {
        T entity = null;
        try
 {
            entity = (T) mapper.getAccountById(String.valueOf(id));
        } catch
 (DataAccessException e) {
            throw
 e;
        }
        return
 entity;
    }
 
    public
 List<T> getList() throws
 DataAccessException {
        return
 (List<T>) mapper.getAllAccount();
    }
}

13、 服务层AccountBiz接口及实现代码

接口:

package
 com.hoo.biz;
 
import
 java.util.List;
<span styl

  


  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics