Spring 和 MyBatis 环境整合

本案例主要是讲述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>
原文地址:https://www.cnblogs.com/xujianbo/p/4941108.html