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>

时间: 2024-10-25 20:44:24

spirngmvc整合mybatis的相关文章

spirngmvc整合mybatis实现CRUD

一.建立一张简单的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 o

SpringBoot 2.SpringBoot整合Mybatis

一.创建Springboot的配置文件:application.properties SpringApplication 会从 application.properties 文件中加载配置信息,下面是添加Spring配置信息的文件目录顺序: 当前目录下的/config子目录中 当前目录中 一个 classpath 包下的 /config 目录中 classpath 根目录中 大家根据自己习惯来即可. /application.properties 文件配置如下: spring.datasourc

spring整合mybatis遇到的bug java.lang.IllegalArgumentException: Property &#39;sqlSessionFactory&#39; or &#39;sqlSessionTemplate&#39; are required

出bug的原因:mybatis-spring版本问题. 查看SqlSessionDaoSupport源码 1.2以上的版本: 1.1.1版本: 解决方法:1.2版本移除了@Autowired的注解,所以如果是1.2版本以上,要在BaseDaoImpl里面手动 注入SetSessionTemplate或者SetSessionFactory spring整合mybatis遇到的bug java.lang.IllegalArgumentException: Property 'sqlSessionFa

springboot学习笔记-2 一些常用的配置以及整合mybatis

一.一些常用的配置 1.1 使用没有父POM的springboot 通过添加scope=import的依赖,仍然能获取到依赖管理的好处: <dependencyManagement> <dependencies> <dependency> <!-- Import dependency management from Spring Boot --> <groupId>org.springframework.boot</groupId>

Spring整合Mybatis应用

1.整合步骤介绍 基于SpringMVC和Mybatis技术开发的主要步骤如下 1>创建工程,搭建SpringMVC和Mybatis技术环境 2>基于MapperScannerConfigurer方式整合Mybatis的Mapper接口(推荐) 3>编写和配置SpringMVC的主要组件,例如Controller,HandlerMapping,ViewResolver等 4>编写JSP视图组件,利用标签和表达式显示模型数据 5>测试程序 2.如何搭建SpringMVC和Myb

Spring整合Mybatis解决 Property &#39;sqlSessionFactory&#39; or &#39;sqlSessionTemplate&#39; are required

在Spring4和Mybatis3整合的时候,dao层注入'sqlSessionFactory'或'sqlSessionTemplate'会报错解决办法如下: package com.alibaba.webx.MyWebxTest.myWebX.module.dao.impl; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionTemplate; import org.m

spring 整合Mybatis 《错误集合,总结更新》

错误:nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor  运行环境:jdk1.7.0_17 + tomcat 7 + eclipse spring整合mybatis启动时候出现這个错误: SEVERE: Exception sending context initialized event to listener instance of class org

Spring mvc整合mybatis基于mysql数据库实现用户增删改查及其分页显示的完整入门实例【转】

Spring mvc整合mybatis例子, 基于mysql数据库实现对用户的增.删.改.查,及分页显示的完整例子. 查询显示用户 添加用户 更新用户 官方验证: 项目截图 必须修改applicationContext.xml中mysql的配置为本地的,否则启动失败. 另外jar包多一个ehcache.jar无关紧要,删除即可. 1. 使用阿里巴巴Druid连接池(高效.功能强大.可扩展性好的数据库连接池.监控数据库访问性能.支持Common-Logging.Log4j和JdkLog,监控数据库

spring源码剖析(八)spring整合mybatis原理

前言 MyBatis相信很多人都会使用,但是当MyBatis整合到了Spring中,我们发现在Spring中使用更加方便了.例如获取Dao的实例,在Spring的我们只需要使用注入的方式就可以了使用Dao了,完全不需要调用SqlSession的getMapper方法去获取Dao的实例,更不需要我们去管理SqlSessionFactory,也不需要去创建SqlSession之类的了,对于插入操作也不需要我们commit. 既然那么方便,Spring到底为我们做了哪些工作呢,它如何将MyBatis整