本案例主要是讲述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. cocos2d-x ios8 输入框显示bug

    https://github.com/cocos2d/cocos2d-x/pull/8149

  2. iOS版 feedly 无法使用gmail账户的解决办法

    印象中很长时间以来,iOS版 Feedly 总是使用不了gmail账户,原因就在于打不开登录界面.但奇怪的是在PC上又正常……非常无语!手机和PC真是两个不同的世界啊 其它RSS阅读软件不是收费,就是 ...

  3. Java 并发之共享对象

    上一篇文章说的是,避免多个线程在同一时间访问对象中的同一数据,这篇文章来详细说说共享和发布对象. 在没有同步的情况下,我们无法预料编译器.处理器安排操作执行的顺序,经常会发生以为“一定会”发生的动作实 ...

  4. 集群搭建:主机宽带拨号上网,虚拟机使用桥接模式,该如何ping通外网

    首先介绍一下看这篇文章需要的基础.需要了解虚拟机的 虚拟机的三种网络模式,有Linux基础知识,这些都是前提.首先介绍一下我的环境:主机:win7虚拟机:VMware Workstation 10虚拟 ...

  5. HDU2196 - Computer(树形DP)

    题目大意 给定一颗n个结点的树,编号为1~n,要求你求出每个结点能到达的最长路径 题解 用动态规划解决的~~~~把1 当成树根,这样就转换成有根树了.我们可以发现,对于每个结点的最长路,要么是从子树得 ...

  6. 使用正则表达式匹配JS函数代码

    使用正则表达式匹配JS函数代码 String someFunction="init"; Pattern regex = Pattern.compile("function ...

  7. ios中view的生命周期

  8. 关于学习Scala语言的一些感悟

    进入话题! 我们知道哈,Spark源码采用Scala语言编写,那么阅读Spark源码之前,是否一定先学Scala呢? 我个人认为,不必,只要我们有一些java或c++编写语言的基础,就可以看Spaar ...

  9. 前景还是“钱景”——MM应用引擎的自我博弈

    纵观当前的移动互联网发展态势,巨大的商机已经展露无遗,各个领域的企业及个人对于APP的开发如火如荼,许多APP从诞生伊始,就面临着软件开发的专业性,商业模式的模糊性,以及市场推广的艰巨性三个巨大难题, ...

  10. JBPM学习(五):流程变量

    1.启动流程实例 // 启动流程实例 @Test public void startProcessInstance() { // 使用指定key的最新版本的流程定义启动流程实例 ProcessInst ...