你的位置:首页 > ASP.net教程

[ASP.net教程]springmvc+spring+mybatis整合实例


开发环境:

System:Windows server 2003

WebBrowser:IE6+、Firefox3+

JavaEE Server:tomcat5.

IDE:eclipse、MyEclipse 6.5

Database:MySQL

开发依赖库:

JavaEE5、Spring 3.0.5、Mybatis 3.0.2、myBatis-spring-1.0.0-rc2

 

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

 源码下载:http://download.csdn.net/detail/nosi79998/6486219

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

 

2、 添加spring的监听及springMVC的核心Servlet,web.复制代码

<!-- 加载Spring容器配置 --> <listener>      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 设置Spring容器加载配置文件路径 --> <context-param>     <param-name>contextConfigLocation</param-name>     <param-value>classpath:applicationContext-*.复制代码

 


3、 在WEB-INF目录中添加spmvc-servlet.复制代码

<beans 复制代码

 


4、 在src目录下添加applicationContext-common.复制代码

<!-- 配置DataSource数据源 -->   <bean id="dataSource" >     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>     <property name="url" value="jdbc:mysql://192.168.1.36:3306/test"/>     <property name="username" value="fssykj"/>     <property name="password" value="fssykj"/>   </bean>  <!-- 配置SqlSessionFactoryBean -->   <bean id="sqlSessionFactory" >    <property name="dataSource" ref="dataSource"/>     <property name="configLocation" value="classpath:mybatis.复制代码

 


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

然后是SqlSessionFactoryBean,这个配置比较关键。SqlSessionFactoryBean需要注入DataSource数据源,其次还要设置configLocation也就是mybatis的

如果使用MapperScannerPostProcessor模式,会自动将basePackage中配置的包路径下的所有带有@Mapper标注的Mapper(dao)层的接口生成代理,替代原来我们的Mapper实现。

5、AccountMapper接口内容如下:

复制代码
@Mapper("mapper") 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);}
复制代码

 


6、 实体类和account-resultmap.复制代码

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.复制代码

<?复制代码

 


7、 在src目录中添加applicationContext-beans.复制代码

<beans 复制代码

 


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

8、 在src目录中添加mybatis.

<?
<!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、 定义AccountDao接口及实现代码,代码如下:

public interface AccountDao<T> {  public boolean addAccount(T entity) throws DataAccessException;  public T getAccount(Integer id) throws DataAccessException;   public List<T> getList() throws DataAccessException;}

 


接口实现

复制代码
import java.util.List;import javax.inject.Inject;import org.springframework.dao.DataAccessException;import org.springframework.stereotype.Repository;import org.springframework.beans.factory.annotation.Autowired;import com.hoo.dao.AccountDao;import com.hoo.entity.*;import com.hoo.mapper.*;import org.springframework.beans.factory.annotation.Qualifier;@SuppressWarnings("unchecked")@Repository("accountDaoImpl")public class AccountDaoImpl<T extends Account> implements AccountDao<T> {  @Autowired(required=false)  @Qualifier("mapper")  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();  }}
复制代码

 


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

接口:

public interface AccountBiz<T> {  public boolean addAccount(T entity) throws DataAccessException;  public T getAccount(Integer id) throws DataAccessException;  public List<T> getList() throws DataAccessException;}

 


实现代码:

复制代码
package com.hoo.biz.impl;import java.util.List;import org.springframework.dao.DataAccessException;import com.hoo.biz.AccountBiz;import com.hoo.entity.*;import javax.inject.Inject;import com.hoo.dao.*;import org.springframework.stereotype.Service;import com.hoo.exception.BizException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;@Service("accountBizImpl")public class AccountBizImpl<T extends Account> implements AccountBiz<T> {  @Autowired  @Qualifier("accountDaoImpl")  private AccountDao<T> dao;  public boolean addAccount(T entity) throws DataAccessException {    if(entity==null){      throw new BizException(Account.class.getName()+"对象参数为empty!");          }    return dao.addAccount(entity);  }  public T getAccount(Integer id) throws DataAccessException {     return dao.getAccount(id);  }  public List getList() throws DataAccessException {    return dao.getList();  }}
复制代码

 


11、 springMVC的控制器,AccountController代码如下:

复制代码
package com.hoo.controller;import javax.inject.Inject;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.beans.factory.annotation.Autowired;import com.hoo.biz.AccountBiz;import com.hoo.entity.Account;import org.springframework.beans.factory.annotation.Qualifier;@Controller("accountController")@RequestMapping("/account")public class AccountController {  @Autowired  @Qualifier("accountBizImpl")  private AccountBiz<Account> biz;   @RequestMapping("/add")  public String add(@RequestParam String username, @RequestParam String password, @RequestParam String status)  {     Integer stat=Integer.valueOf(status);    Account acc=new Account(username,password,stat);       System.out.println(acc);    biz.addAccount(acc);    return "redirect:/account/list.do";  }  @RequestMapping("/get")  public String get(Integer id,Model model)  {    System.out.println("###ID:"+id);    model.addAttribute(biz.getAccount(id));    return "/show.jsp";  }  @RequestMapping("/list")  public String list(Model model)  {    model.addAttribute("list",biz.getList());    return "/list.jsp";  }  @ExceptionHandler(Exception.class)  public String exception(Exception e,HttpServletRequest request)  {    request.setAttribute("exception", e);    return "/error.jsp";  }}
复制代码

 


12、 基本页面代码

index.jsp

<body>   <h3>整合springmvc3.2+spring+mybatis3.2</h3>   <a href="account/list.do">查询所有</a><br/>   <a href="account/add.do?username=abcdef&password=123132&status=2">添加</a><br>   <a href="account/get.do?id=2">查询</a><br> </body>

 


List.jsp

复制代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head>    <title>My JSP 'list.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">  <meta http-equiv="cache-control" content="no-cache">  <meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  <meta http-equiv="description" content="This is my page">  <!--  <link rel="stylesheet" type="text/css" href="styles.css">  --> </head>  <body>  <c:forEach items="${list}" var="data">  id:${data.accountId }--name:${data.username }--password:  ${data.password }<hr/>  </c:forEach> </body></html>
复制代码

 


show.jsp

 <body>
    ${account }<br>
    ${account.username }#${account.accountId }
  </body>

error.jsp

 <body>
    <h2>Exception:${exception }</h2>
    <a href="javascript:document.getElementById('show').style.display='block';void(0);">详细信息</a>
    <div id="show" >
      <% Exception ex=(Exception)request.getAttribute("exception"); %>
      <%ex.printStackTrace(new PrintWriter(out)); %>
    </div>
  </body>

13、 以上就基本上完成了整个Spring+SpringMVC+MyBatis的整合了。如果你想添加事务管理,得在applicationContext-common.

<!-- 配置事务管理器,注意这里的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事务就没有作用了 -->
<bean id="transactionManager" >
    <property name="dataSource" ref="dataSource" />
</bean>


同时还需要加入aspectjweaver.jar这个jar包;

注意的是:Jdbc的TransactionManager不支持事务隔离级别,我在整个地方加入其它的TransactionManager,增加对transaction的隔离级别都尝试失败!

也许可以用于jpa、jdo、jta这方面的东西。

请参考一下资料下载源码:

http://www.spring.net