spirngmvc整合mybatis

一、建立一张简单的User表

CREATE TABLE `users` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`age` int(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', '杜崇', '10');
INSERT INTO `users` VALUES ('2', '黄春宇', '12');
INSERT INTO `users` VALUES ('11', '文杰', '2');
INSERT INTO `users` VALUES ('12', '何亮', '20');
INSERT INTO `users` VALUES ('13', '超哥', '25');
INSERT INTO `users` VALUES ('14', '阿宝', '10');

二、用myeclipse建立一个web工程ssi

2.1、jar包

2.2目录结构

2.3、springmvc的核心servlet  ssi-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

<context:component-scan base-package="org.ssi.controller"/>
<!--自动注册解析器和适配器-->
<mvc:annotation-driven/>
<mvc:default-servlet-handler />
<aop:aspectj-autoproxy proxy-target-class="true" /> 
<!-- 视图解析器的分配器 -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<!--先检查请求的后缀名,如果没有匹配的,则spring检查请求头里面设置的  ContentType 来找适合的 mediaType来返回一种 mediaType 
mediaTypes这个属性存储了 你请求后缀名 或者 参数 所对应 的mediaType
-->
<property name="mediaTypes">
<map>
<entry key="atom" value="application/atom+xml"/>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
<!--具体的解析器 -->
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>

</beans>

2.4、 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>ssi</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>ssi</servlet-name>
<url-pattern>/</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>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>

<session-config>
<session-timeout>0</session-timeout>
</session-config>
</web-app>

2.5、conf.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="org.ssi.model.User" alias="User"/>
</typeAliases>
</configuration>

2.6、配置spring容器 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
">
<!-- 加载数据库属性配置文件 
<context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/>
-->

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!--
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property> 
-->
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property> 
<!--maxActive: 最大连接数量--> 
<property name="maxActive" value="150"/> 
<!--minIdle: 最小空闲连接--> 
<property name="minIdle" value="5"/> 
<!--maxIdle: 最大空闲连接--> 
<property name="maxIdle" value="20"/> 
<!--initialSize: 初始化连接--> 
<property name="initialSize" value="30"/> 
<!-- 连接被泄露时是否打印 --> 
<property name="logAbandoned" value="true"/> 
<!--removeAbandoned: 是否自动回收超时连接--> 
<property name="removeAbandoned" value="true"/> 
<!--removeAbandonedTimeout: 超时时间(以秒数为单位)--> 
<property name="removeAbandonedTimeout" value="10"/> 
<!--maxWait: 超时等待时间以毫秒为单位 1000等于60秒--> 
<property name="maxWait" value="1000"/> 
<!-- 在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位. --> 
<property name="timeBetweenEvictionRunsMillis" value="10000"/> 
<!-- 在每次空闲连接回收器线程(如果有)运行时检查的连接数量 --> 
<property name="numTestsPerEvictionRun" value="10"/> 
<!-- 1000 * 60 * 30 连接在池中保持空闲而不被空闲连接回收器线程--> 
<property name="minEvictableIdleTimeMillis" value="10000"/> 
</bean>


<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
<property name="configLocation" value="classpath:conf.xml" /> 
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:org/ssi/mapper/*.xml" />
</bean>
<!-- 配置扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描org.ssi.dao这个包以及它的子包下的所有映射接口类 -->
<property name="basePackage" value="org.ssi.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean> 

<!--配置事物 -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager ">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 注解事务-->
<tx:annotation-driven transaction-manager="txManager" />
<context:annotation-config />
<!-- 
-->
<context:component-scan base-package="org.ssi.service,org.ssi.dao," />
</beans>

2.7、dao接口,不用提供实现类,实现类有mybatis实现

package org.ssi.dao;

import java.util.List;

import org.ssi.model.User;


public interface UserMapperI {

/**
* 增
* @param user
*/
public void addUser(User user);
/**
* 改
* @param user
*/
public void updateUser(User user);
/**
* 删
* @param id
*/
public void deleteUser(int id);
/**
* 查
* @param id
* @return
*/
public User getUser(int id);
/**
* 查所有
* @return
*/
public List<User> getAllUsers();

}

与配置文件中的类文件以及路径相对应,

2.8、pojo类 user.java

package org.ssi.model;

public class User {

private int id;
private String name;
private int age;

public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}

public User() {
super();
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}

}

2.9、UserMapperI.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
例如namespace="org.ssi.dao.UserMapperI"就是org.ssi.dao(包名)+UserMapperI(userMapperI.xml文件去除后缀)
-->
<mapper namespace="org.ssi.dao.UserMapperI">
<!-- <resultMap>标签用来处理pojo对象的属性与表字段之间的不匹配问题
<resultMap id="userResultMap" type="User">
<id property="id" column="userid" />
<result property="name" column="username" />
<result property="age" column="age" />
</resultMap>
-->
<!-- 
在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,
不能够重复 使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
resultType="org.mybatis.model.User"就表示将查询结果封装成一个User类的对象返回
User类就是users表所对应的实体类
-->
<!-- 
根据id查询得到一个user对象
--> 
<select id="getUser" parameterType="int" 
resultType="User">
select * from users where id=#{id}
</select>

<insert id="addUser" parameterType="User" >
insert into users(name ,age) values(#{name},#{age})
</insert>

<delete id="deleteUser" parameterType="int">
delete from users where id=#{id}
</delete>

<update id="updateUser" parameterType="User">
update users set name=#{name},age=#{age} where id=#{id}
</update>

<select id="getAllUsers" resultType="User">
select * from users
</select>
</mapper>

该xml文件中的各种操作的id必须要跟dao接口中的方法名字一一对应,否侧会报错。

按照以上配置,springmvc整合mybatis的整体架构已经完成,

三、编写代码进行测试

Controller控制器  SsiController.java

package org.ssi.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.ssi.dao.UserMapperI;
import org.ssi.model.User;

@Controller
@RequestMapping(value="/controller")
public class SsiController {

@Autowired
private UserMapperI umi;
private List<User> ulist; 

@RequestMapping(value="/all",method = RequestMethod.GET)
public String uList(HttpServletRequest request){

ulist=this.umi.getAllUsers();
for (int i = 0; i < ulist.size(); i++) {
System.out.println(ulist.get(i));
}
request.setAttribute("ulist",ulist);
return "allusers";

}


@RequestMapping(value = "/addu", method = RequestMethod.POST)
public String addU(User u) {

this.umi.addUser(u);
return "redirect:all";
}

@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String deleteU(HttpServletRequest request,@PathVariable Integer id) {

this.umi.deleteUser(id);
return "redirect:/controller/all";
}

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public String getUserById(HttpServletRequest request,@PathVariable Integer id) {

User u=this.umi.getUser(id);
request.setAttribute("user", u);
return "userinfo";
}

@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
public String updateU(HttpServletRequest request,@PathVariable Integer id,User u) {

User uu=this.umi.getUser(id);
uu.setName(u.getName());
uu.setAge(u.getAge());
this.umi.updateUser(uu);
return "redirect:/controller/all";
}
}

3.1、测试新增

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>Add User</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>


<form action="controller/addu" method="post">
name : <input name="name" type="text"><br>
age : <input name="age" type="text"><br>
<input type="submit" value="submit">
</form>
<br>


</body>
</html>

添加前:

 

添加:

添加后:

 

点击edit 19 奥巴马

userinfo.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>UserInfo</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>
<p align="center"><font size="20">UserInfo Edit</font></p>
<div align="center">
<form action="controller/update/${user.id}" method="post">
Name :<input type="text" name="name" value="${user.name}"><br>
Age :<input type="text" name="age" value="${user.age }"><br>
<input type="submit" value="Usubmit"> 
</form>
</div>
</body>
</html>

原文地址:https://www.cnblogs.com/dry0515/p/5175407.html