开发环境:
System:Windows 7
WebBrowser:IE8+、Firefox3+
JavaEE Server:tomcat7.
IDE:eclipse、MyEclipse 6.5
Database:MySQL
在阅读文章之前,请熟悉Spring、SpringMVC、MyBatis
源码下载地址:
(工程在Eclipse中的m2eclipse插件中构建,最新版的Eclipse for Javaee中自带m2eclipse)
工程分为三个部分:
1、 首先新建一个WebProject 命名为ssi,新建项目时,使用JavaEE5的lib库。然后手动添加需要的jar包,所需jar包如下:
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>
<!--配置Springmvc核心控制器-->
<servlet>
<servlet-name>spmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<!--为DispatcherServlet建立映射 -->
<servlet-mapping>
<servlet-name>spmvc</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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
3、 在WEB-INF目录中添加spmvc-servlet.xml,内容如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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,内容如下:
<!-- 配置DataSource数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<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" 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/mapper/*.xml</value >
</list>
</property>
</bean>
<!-- 通过扫描的模式,扫描目录在com/hoo/mapper目录下 -->
<bean class="org.mybatis.spring.annotation.MapperScannerPostProcessor">
<property name="basePackage" value="com.hoo.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
上面的配置最先配置的是DataSource,这里采用的是jdbc的DataSource;
然后是SqlSessionFactoryBean,这个配置比较关键。SqlSessionFactoryBean需要注入DataSource数据源,其次还要设置configLocation也就是mybatis的xml配置文件路径,完成一些关于mybatis的配置,如settings、mappers、plugin等;
如果使用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.xml
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">
<!-- namespace和定义的Mapper接口对应,并实现其中的方法 -->
<mapper namespace="com.hoo.mapper.AccountMapper">
<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>
<!-- 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="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>
7、 在src目录中添加applicationContext-beans.xml内容如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
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、 定义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" style="color:red;display:none;">
<% Exception ex=(Exception)request.getAttribute("exception"); %>
<%ex.printStackTrace(new PrintWriter(out)); %>
</div>
</body>
13、 以上就基本上完成了整个Spring+SpringMVC+MyBatis的整合了。如果你想添加事务管理,得在applicationContext-common.xml中加入如下配置:
<!-- 配置事务管理器,注意这里的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事务就没有作用了 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
同时还需要加入aspectjweaver.jar这个jar包;
注意的是:Jdbc的TransactionManager不支持事务隔离级别,我在整个地方加入其它的TransactionManager,增加对transaction的隔离级别都尝试失败!
也许可以用于jpa、jdo、jta这方面的东西。