本案例主要是讲述Spring  和  MyBatis 的环境整合 , 对页面功能的实现并没有做的很完整

先附上本案例的结构

1 . 创建项目并导入相关jar包

commons-collections4-4.0.jar
commons-dbcp2-2.1.1.jar
commons-fileupload.jar
commons-io.jar
commons-logging-1.2.jar
commons-pool2-2.4.2.jar
jstl-1.2.jar
junit-4.10.jar
mybatis-3.1.1.jar
mybatis-spring-1.2.1.jar
mysql-connector-java-5.1.26-bin.jar
spring-beans-3.2.8.RELEASE.jar
spring-context-3.2.8.RELEASE.jar
spring-context-support-3.2.8.RELEASE.jar
spring-core-3.2.8.RELEASE.jar
spring-expression-3.2.8.RELEASE.jar
spring-jdbc-3.2.8.RELEASE.jar
spring-tx-3.2.8.RELEASE.jar
spring-web-3.2.8.RELEASE.jar
spring-webmvc-3.2.8.RELEASE.jar
standard-1.1.2.jar

2 . 创建一个数据表

create database springmybatis;
use springmybatis ;
create table t_product (
p_id int(11) primary key auto_increment ,
p_title varchar(100) ,
p_price double(11,2) ,
p_store int(11) ,
p_img varchar(200)
) ; insert into t_product(
p_title , p_price , p_store , p_img
) values (
'香甜可口的大柚子快来买吧过了这村没这个店' ,
10.00,
500,
'p-big-123.jpg'
) ;

3 . 创建一个商品类

package com.springmybatis.entity;

import java.io.Serializable;

public class Product implements Serializable{

    private static final long serialVersionUID = -6233090527088205803L;

    private int p_id;//商品编号
private String p_title;//商品标题
private double p_price;//商品价格
private int p_store;//商品库存
private String p_img;//商品图片
public Product() {
}
public Product(int p_id, String p_title, double p_price, int p_store, String p_img) {
this.p_id = p_id;
this.p_title = p_title;
this.p_price = p_price;
this.p_store = p_store;
this.p_img = p_img;
}
public int getP_id() {
return p_id;
}
public void setP_id(int p_id) {
this.p_id = p_id;
} public String getP_title() {
return p_title;
} public void setP_title(String p_title) {
this.p_title = p_title;
}
public double getP_price() {
return p_price;
}
public void setP_price(double p_price) {
this.p_price = p_price;
}
public int getP_store() {
return p_store;
}
public void setP_store(int p_store) {
this.p_store = p_store;
}
public String getP_img() {
return p_img;
}
public void setP_img(String p_img) {
this.p_img = p_img;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "Product [p_id=" + p_id + ", p_title=" + p_title + ", p_price=" + p_price + ", p_store=" + p_store + ", p_img=" + p_img + "]";
}
}

4 . 创建自定义注解

package com.springmybatis.annotation;

//自定义注解
public @interface SpringMybatisAnnotation { String value() default ""; }

5 . 创建映射接口  ProductMapper

package com.springmybatis.mapper;

import java.util.List;

import org.springframework.stereotype.Component;

import com.springmybatis.annotation.SpringMybatisAnnotation;
import com.springmybatis.entity.Product; @SpringMybatisAnnotation
//@Component 也可使用Spring自己的注解
public interface ProductMapper { List<Product> findAll(); void update(Product product); }

6 . 创建映射文件  ProductMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.springmybatis.mapper.ProductMapper"> <select id="findAll" resultType="com.springmybatis.entity.Product">
select * from t_product
</select> <update id="update" parameterType="com.springmybatis.entity.Product">
update t_product set p_title=#{p_title}, p_price=#{p_price}, p_store=#{p_store},
p_img=#{p_img} where p_id=#{p_id}
</update> </mapper>

7 . 创建DAO接口 ProductDAO.java

package com.springmybatis.dao;

import java.util.List;

import com.springmybatis.entity.Product;

public interface ProductDAO {

    List<Product> findAll();

    void update(Product product);

}

8 . 创建DAO的实现类

package com.springmybatis.dao;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.springmybatis.entity.Product;
import com.springmybatis.mapper.ProductMapper; @Repository("productDAO")
public class ProductDAOImpl implements ProductDAO {
@Resource
private ProductMapper productMapper;
@Override
public List<Product> findAll() {
return productMapper.findAll();
}
@Override
public void update(Product product) {
productMapper.update(product);
}
}

9 . 创建service接口  ProductService.java

package com.springmybatis.service;

import java.util.List;

import com.springmybatis.entity.Product;

public interface ProductService {

    List<Product> findAll();

    void update(Product product);

}

10 . 创建service的实现类   ProductServiceImpl.java

package com.springmybatis.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.springmybatis.dao.ProductDAO;
import com.springmybatis.entity.Product;
@Service("productService")
public class ProductServiceImpl implements ProductService { @Resource
private ProductDAO productDAO; @Override
public List<Product> findAll() { return productDAO.findAll();
} @Override
public void update(Product product) {
productDAO.update(product); } }

11 . 编写控制器  ProductController.java

package com.springmybatis.controller;

import java.io.File;
import java.io.IOException;
import java.util.List; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; import com.springmybatis.entity.Product;
import com.springmybatis.service.ProductService; @Controller
@RequestMapping("/product")
public class ProductController { @Resource
private ProductService productService; @RequestMapping("/list")
public String findAll(Model model){
List<Product> products = productService.findAll();
model.addAttribute("products",products);
return "product/list";
} @RequestMapping("/load")
public String load(HttpServletRequest request, Model model){
int p_id = Integer.valueOf(request.getParameter("p_id").toString());
model.addAttribute("p_id",p_id);
return "product/load";
} //文件上传
@RequestMapping("/submitload")
public String submitLoad(@RequestParam("product_img") MultipartFile product_img, Product product, HttpServletRequest request) throws IOException{
String realPath = request.getSession().getServletContext().getRealPath("/img");
product.setP_img(product_img.getOriginalFilename());
//System.out.println(realPath);
FileUtils.copyInputStreamToFile(product_img.getInputStream(),new File(realPath, product_img.getOriginalFilename()));
//System.out.println(product);
productService.update(product);
return "redirect:/product/list";
}
}

12 . 在src下  创建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: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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 开启Spring注解 -->
<context:component-scan base-package="com.springmybatis.controller"></context:component-scan>
<context:component-scan base-package="com.springmybatis.service"></context:component-scan>
<context:component-scan base-package="com.springmybatis.dao"></context:component-scan> <!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean> <!-- 加载数据库连接参数配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置dataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> <!-- 配置 sqlSessionFactory -->
<!--
SqlSessionFactoryBean
为整合应用提供SqlSession对象资源
在单独使用Mybatis时,所有操作都时围绕SqlSession展开,SqlSession是通过SqlSessionFactory获取的,
SqlSessionFactory又是通过SqlSessionFactoryBuilder创建生成的。
在Spring和Mybatis整合应用时,同样需要SqlSession,mybatis-spring-1.2.1.jar提供了一个SqlSessionFactoryBean 。
这个组件作用就是通过SqlSessionFactoryBuilder生成SqlSessionFactory对象,为整合应用提供SqlSession对象。
必须为其注入:DataSource 和 映射文件位置
属性介绍:
dataSource
用于连接数据库的数据源(required)
mapperLocations
用于指定Mapper文件存放的位置
configLocation
用于指定mybatis的配置文件位置,如果制定了该属性,那么会以该配置文件的内容作为配置信息构建对应的SqlSessionFactoryBuiler,
但是后续属性指定的内容会被覆盖
typeAliasesPackage
它一般对应我们的实体类所在的包,它会自动取对应的包中不包括包名的简单类名作为包括包名的类别名,
多个package之间可以用逗号或者分号分隔
typeAliases
它是数组类型,用来指定别名的,指定这个属性后,mybatis会把这个类型的短名称作为这个类型的别名 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:com/springmybatis/mapperxml/*.xml"></property>
<!-- <property name="configLocation" value="classpath:SqlMapConfig.xml"></property> -->
</bean> <!-- 配置映射扫描范围 -->
<!--
MapperScannerConfigurer
根据指定包批量扫描Mapper接口并生成实例
在定义这个bean时,只需要指定一个basePackage即可,
basePackage
用于指定Mapper接口所在的包,在这个包及其所有子包下面的Mapper接口都将被搜索到,
并把他们注册为一个一个映射工厂bean
多个包之间而已使用逗号或者分号进行分隔。
SqlSessionFactory
该属性可以不用指定,会以Autowired方式自动注入 如果指定的某个包下并不完全是我们定义的Mapper接口,此时使用MapperScannerConfigurer的另外两个属性可以缩小搜索和注册的范围,
annotationClass :
用于指定一个注解标记,当指定了该属性时,MapperScannerConfigurer将只注册使用了annotationClass注解标记的接口
markerInterface :
用于指定一个接口,当指定了该属性,MapperScannerConfigurer将只注册标记了该注解的接口
如果以上两者都配置了,去并集 而不是交集
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.springmybatis.mapper"></property>
<!-- <property name="annotationClass" value="com.springmybatis.annotation.SpringMybatisAnnotation"></property> -->
</bean> <!--
     spring mvc对文件上传的支持工具 建立在导入的两个jar包之上
     commons-fileupload.jar
     commons-io.jar
   -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="1024000"></property>
</bean> </beans>

13 . 在src下  创建mybatis 主配置文件  SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
<!--
    该条配置也可以在applicationContext.xml中的sqlSessionFactory的locations属性上定义
    本例就是在applicationContext.xml里配置的
<mappers>
<mapper resource="classpath:com/springmybatis/mapperxml/*.xml"/>
</mappers>
-->
</configuration>

14 . 配置 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Mybatis_day02</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--
若不配置该初始化参数 spring会自动去找"/WEB-INF/<servlet-name>-servlet.xml"
若配置了如下的初始化参数,Spring MVC框架将加载"classpath:applicationContext.xml"来进行初始化上下文
而不是"/WEB-INF/<servlet-name>-servlet.xml"
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 解决中文乱码问题 -->
<filter>
<filter-name>spring-filter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>spring-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 放行静态资源 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping> </web-app>

--------------------------------下面是需要的页面 -----------------------------------------------

结构如下

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<title>Insert title here</title>
</head>
<body>
<a href="<%=basePath%>product/list">查看所有产品信息</a>
</body>
</html>

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<title>Insert title here</title>
</head>
<body>
<h1>商品信息</h1>
<table>
<thead>
<tr>
<th>No.</th>
<th>ID</th>
<th>TITLE</th>
<th>PRICE</th>
<th>STORE</th>
<th>IMG</th>
<th>OPERATION</th>
</tr>
</thead>
<tbody>
<c:forEach items="${products }" var="product" varStatus="stat">
<tr>
<td>${stat.count }</td>
<td>${product.p_id}</td>
<td>${product.p_title}</td>
<td>${product.p_price}</td>
<td>${product.p_store}</td>
<td>
<img alt="" src="<%=basePath%>img/${product.p_img}" width="40">
</td>
<td>
<a href="<%=basePath%>product/load?p_id=${product.p_id}">修改</a>
<a href="<%=basePath%>product/delete?p_id=${product.p_id}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table> </body>
</html>

load.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<title>Insert title here</title>
</head>
<body>
<form action="product/submitload?p_id=${p_id }" method="post" enctype="multipart/form-data">
标题: <input type="text" name="p_title"><br><br>
价格: <input type="text" name="p_price"><br><br>
库存: <input type="text" name="p_store"><br><br>
文件: <input type="file" name="product_img"><br><br>
<input type="submit" value="提交">
</form>
</body>
</html>

Spring 和 MyBatis 环境整合的更多相关文章

  1. Spring和MyBatis环境整合

    SSH框架的结合几乎家喻户晓,但是一般的中小项目,使用Spring和MyBatis就够了,而且MyBatis轻便好使,易上手,值得大家尝试一次. 开篇简介: Spring: Spring是一个轻量级的 ...

  2. idea spring+springmvc+mybatis环境配置整合详解

    idea spring+springmvc+mybatis环境配置整合详解 1.配置整合前所需准备的环境: 1.1:jdk1.8 1.2:idea2017.1.5 1.3:Maven 3.5.2 2. ...

  3. Spring+SpringMVC+MyBatis+easyUI整合优化篇(二)Log4j讲解与整合

    日常啰嗦 上一篇文章主要讲述了一下syso和Log间的一些区别与比较,重点是在项目的日志功能上,因此,承接前文<Spring+SpringMVC+MyBatis+easyUI整合优化篇(一)Sy ...

  4. Spring+SpringMVC+MyBatis+easyUI整合优化篇(五)结合MockMvc进行服务端的单元测试

    日常啰嗦 承接前一篇文章<Spring+SpringMVC+MyBatis+easyUI整合优化篇(四)单元测试实例>,已经讲解了dao层和service层的单元测试,还有控制器这层也不能 ...

  5. Spring+SpringMVC+MyBatis的整合

    1.基本概念   1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-On ...

  6. Spring+SpringMVC+MyBatis+easyUI整合进阶篇(七)一次线上Mysql数据库崩溃事故的记录

    作者:13 GitHub:https://github.com/ZHENFENG13 版权声明:本文为原创文章,未经允许不得转载. 文章简介 工作这几年,技术栈在不断更新,项目管理心得也增加了不少,写 ...

  7. SSM(Spring,SpringMVC,Mybatis)框架整合项目

    快速上手SSM(Spring,SpringMVC,Mybatis)框架整合项目 环境要求: IDEA MySQL 8.0.25 Tomcat 9 Maven 3.6 数据库环境: 创建一个存放书籍数据 ...

  8. 关于Spring和mybatis的整合

    Spring同Mybatis的整合 1.引入相应的jar包.(Mybatis的jar包,Spring的jar包,mybatis-spring-1.1.1.jar). 2.编写相应的包(三层的包).搭建 ...

  9. 基于maven进行spring 和mybatis的整合(Myeclpise)

    学习日记:基于maven进行spring和mybatis的整合,进行分页查询 什么是maven:maven是一个项目管理工具,使用maven可以自动管理java项目的整个生命周期,包括编译.构建.测试 ...

随机推荐

  1. opencv保存选择图像中的区域

    在自己建立行人检测的图像库时用到,参考别人的修改了一下: #include "opencv2/core/core.hpp" #include "opencv2/highg ...

  2. yarn环境的搭建

    1.首先,在zookeeper搭建成功,服务运行的基础上搭建yarn,其次,保证时间一致 2.在 /home/install/hadoop-2.5/etc/hadoop目录下配置一下几个配置文件: 第 ...

  3. 【HTML】Advanced2:Conditional Comments

    1.try and figure out what is sensible for you to support. Are your web site visitors likely to be us ...

  4. codeforce 621A Wet Shark and Odd and Even

    水 最大偶数和 #include<iostream> #include<string> #include<algorithm> #include<cstdli ...

  5. Weblogic 集群部署说明 --转

    代理web.xml 设置 <servlet> l                <servlet-name>HttpClusterServlet</servlet-nam ...

  6. 用户名 不在 sudoers文件中,此事将被报告

    解决方法: 1.通过编辑器来打开/etc/sudoers 2.直接使用命令visudo 打开sudoers后,如下加上自己的帐号保存后就可以了. # User privilege specificat ...

  7. ehcharts中国地图四级级下钻

    echarts 官网关于中国地图,只有全国-省:省-市,没有中国-省-市-县四级下钻相关文献,echarts地图最重要一点是模块化相对于其他各个图形,一下为三级下钻部分代码包括各级别交互,望指点: 中 ...

  8. 常用的windowd属性和对象

    window.location.href=""          指向一个定向的url并提交数据过去 window.location.reload()         强制刷新当前 ...

  9. eclipse调试的基本意义

    step into就是单步执行,遇到子函数就进入并且继续单步执行: step over是在单步执行时,在函数内遇到子函数时不会进入子函数内单步执行,而是将子函数整个执行完再停止,也就是把子函数整个作为 ...

  10. SpringMVC经典系列-13使用SpringMVC处理Ajax请求---【LinusZhu】

    注意:此文章是个人原创,希望有转载须要的朋友们标明文章出处,假设各位朋友们认为写的还好,就给个赞哈,你的鼓舞是我创作的最大动力,LinusZhu在此表示十分感谢,当然文章中如有纰漏,请联系linusz ...