一、建立一张简单的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 ('', '杜崇', '');
INSERT INTO `users` VALUES ('', '黄春宇', '');
INSERT INTO `users` VALUES ('', '文杰', '');
INSERT INTO `users` VALUES ('', '何亮', '');
INSERT INTO `users` VALUES ('', '超哥', '');
INSERT INTO `users` VALUES ('', '阿宝', '');

二、用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>

spirngmvc整合mybatis实现CRUD的更多相关文章

  1. SpringBoot 整合 Mybatis 进行CRUD测试开发

    今天来和大家分享下 Spring Boot 整合 MyBatis 的 CRUD 测试方法开发.因为 MyBaits 有两种开发形式,一种基于注解,一种基于 xml . SpringBoot配置文件也有 ...

  2. spirngmvc整合mybatis

    一.建立一张简单的User表 CREATE TABLE `users` (`id` int(20) NOT NULL AUTO_INCREMENT,`name` varchar(20) NOT NUL ...

  3. Spring boot 入门四:spring boot 整合mybatis 实现CRUD操作

    开发环境延续上一节的开发环境这里不再做介绍 添加mybatis依赖 <dependency> <groupId>org.mybatis.spring.boot</grou ...

  4. 【java框架】SpringBoot(7) -- SpringBoot整合MyBatis

    1.整合MyBatis操作 前面一篇提到了SpringBoot整合基础的数据源JDBC.Druid操作,实际项目中更常用的还是MyBatis框架,而SpringBoot整合MyBatis进行CRUD也 ...

  5. Spring Boot整合Mybatis并完成CRUD操作

    MyBatis 是一款优秀的持久层框架,被各大互联网公司使用,本文使用Spring Boot整合Mybatis,并完成CRUD操作. 为什么要使用Mybatis?我们需要掌握Mybatis吗? 说的官 ...

  6. Springboot整合Mybatis实现级联一对多CRUD操作

    在关系型数据库中,随处可见表之间的连接,对级联的表进行增删改查也是程序员必备的基础技能.关于Spring Boot整合Mybatis在之前已经详细写过,不熟悉的可以回顾Spring Boot整合Myb ...

  7. Spring Boot整合Mybatis完成级联一对多CRUD操作

    在关系型数据库中,随处可见表之间的连接,对级联的表进行增删改查也是程序员必备的基础技能.关于Spring Boot整合Mybatis在之前已经详细写过,不熟悉的可以回顾Spring Boot整合Myb ...

  8. Spring Boot 整合 Mybatis Annotation 注解的完整 Web 案例

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 公司需要人.产品.业务和方向,方向又要人.产品.业务和方向,方向… 循环』 本文提纲一. ...

  9. SpringBoot 2.x (9):整合Mybatis注解实战

    SSM框架再熟悉不过了,不过以前通常是使用XML写SQL语句 这里用SpringBoot整合Mybatis并且使用注解进行开发 依赖: <!-- Mybatis --> <depen ...

随机推荐

  1. qemu-kvm 代码分析

    qemu-kvm 代码分析 虚拟机组成 实际上面所说计算机组成比较笼统,实际处理器,存储器,输入与设备种类繁多,     -   i440FX host PCI bridge and PIIX3 PC ...

  2. windows下如何查看端口占用

    1.查看端口使用情况netstat -aon(以3306为例) 2.根据3306端口号查看对应的进程号(进程号就是进程的唯一标识,根据这个进程号就能找到对应的应用) 3.根据进程号查询相应的应用占用端 ...

  3. js的深拷贝特别注意this的深拷贝

    原生的,jquery的extend,和angular的copy 我们深拷贝的根本原因是为了不改变原来对象的值. <script type="text/javascript"& ...

  4. Template、ItemsPanel、ItemContainerStyle、ItemTemplate(包括ListBox的Item子项是横向排列)

    Template.ItemsPanel.ItemContainerStyle.ItemTemplate 分类: WPF2011-10-12 10:13 4716人阅读 评论(0) 收藏 举报 data ...

  5. SpringBoot使用devtools导致的类型转换异常

    遇到的问题:SpringBoot项目中的热部署引发的血的教训,报错代码位置: XStream xStream1 = new XStream(); xStream1.autodetectAnnotati ...

  6. ng-file-upload - samples

    <script src="angular.min.js"></script> <!-- shim is needed to support non-H ...

  7. 16 Python 递归函数

    递归 1.什么是递归 recursion 递归 递归的定义——在一个函数里再调用这个函数本身 在一个函数里再调用这个函数本身,这种魔性的使用函数的方式就叫做递归. 递归的最大深度——997 一个函数在 ...

  8. LeetCode OJ:Validate Binary Search Tree(合法的二叉搜索树)

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  9. Engineer manager

    your tasks and responsibilities Position: Major Tasks  Lead site project management to ensure all p ...

  10. POJ - 2891 Strange Way to Express Integers (扩展中国剩余定理)

    题目链接 扩展CRT模板题,原理及证明见传送门(引用) #include<cstdio> #include<algorithm> using namespace std; ty ...