开辟景象:
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内容,内容如下:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class> listener> <context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:applicationContext-*.xmlparam-value> context-param> <servlet> <servlet-name>spmvcservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> servlet> <servlet-mapping> <servlet-name>spmvcservlet-name> <url-pattern>*.dourl-pattern> servlet-mapping> <filter> <filter-name>CharacterEncodingFilterfilter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class> <init-param> <param-name>encodingparam-name> <param-value>utf-8param-value> init-param> filter> <filter-mapping> <filter-name>CharacterEncodingFilterfilter-name> <url-pattern>/*url-pattern> filter-mapping> <welcome-file-list> <welcome-file>index.jspwelcome-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" /> <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,内容如下:
<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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis.xml"/> <property name="mapperLocations"> <list> <value> classpath:com/hoo/mapper/*.xmlvalue > list> property> bean> <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 ListgetAllAccount(); 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"> <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="getAccount" resultType="account"> * account limit 1 ]]> > < id="getAllAccount" resultType="list" resultMap="accountResultMap"> * account ]]> > < id="getAccountById" parameterType="string" resultType="com.hoo.entity.Account" resultMap="accountResultMap"> * account where account_id = #{id} ]]> > < id="getAccountByNames" parameterType="string" resultMap="accountResultMap"> * account where username = #{name} ]]> > <sql id="user_name_pwd"> username, password sql> < id="addAccount" useGeneratedKeys="true" keyProperty="account_id" parameterType="account"> into account(account_id, status, username, password) values(#{accountId}, #{status}, #{username}, #{password}) > < 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"> <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{ public boolean addAccount(T entity) throws DataAccessException; public T getAccount(Integer id) throws DataAccessException; public List 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 AccountDaoImplextends Account> implements AccountDao { @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 getList() throws DataAccessException { return (List )mapper.getAllAccount(); } }
10、 办事层AccountBiz接口及实现代码
接口:
public interface AccountBiz{ public boolean addAccount(T entity) throws DataAccessException; public T getAccount(Integer id) throws DataAccessException; public List 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 AccountBizImplextends Account> implements AccountBiz { @Autowired @Qualifier("accountDaoImpl") private AccountDao 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 AccountBizbiz; @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.2h3> <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 pagetitle> <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"> 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
13、 以上就根蒂根基上完成了全部Spring+SpringMVC+MyBatis的整合了。若是你想添加事务经管,得在applicationContext-common.xml中参加如下设备:
<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