开辟景象:
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.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(" * 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中的别号 --> < id="getAccount" resultType="account"> <![CDATA[ * account limit 1 ]]> </> < id="getAllAccount" resultType="list" resultMap="accountResultMap"> <![CDATA[ * account ]]> </> <!-- accountResultMap是account-resultmap.xml中定义的resultmap --> < id="getAccountById" parameterType="string" resultType="com.hoo.entity.Account" resultMap="accountResultMap"> <![CDATA[ * account where account_id = #{id} ]]> </> <!-- accountMap.accountResultMap是account-resultmap.xml中定义的resultmap,经由过程namespace.id找到 --> < id="getAccountByNames" parameterType="string" resultMap="accountResultMap"> <![CDATA[ * account where username = #{name} ]]> </> <sql id="user_name_pwd"> username, password </sql> <!-- 主动生成id策略 --> < id="addAccount" useGeneratedKeys="true" keyProperty="account_id" parameterType="account"> into account(account_id, status, username, password) values(#{accountId}, #{status}, #{username}, #{password}) </> <!-- 按照Key语句生成主键 --> < id="addAccount4Key" parameterType="account"> <Key keyProperty="account_id" order="BEFORE" resultType="int"> cast(random() * 10000 as Integer) a #Tab </Key> into account(account_id, status, username, password) values(#{accountId}, #{status}, #{username}, #{password}) </> < id="editAccount" parameterType="account"> account set status = #{status}, username = #{username}, password = #{password} where account_id = #{accountId} </> < id="removeAccount" parameterType="int"> account where account_id = #{id} </> </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
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这方面的器材。
地址:http://download.csdn.net/detail/nosi79998/6486219
经测试可以运行,迎接进修。