Spring+Mybatis整合案例电商模块

框架整合

  • 导入项目的配置依赖到pom.xml文件中
  • 项目分层,创建实体类,创建Mybatis的持久层接口及映射文件
  • 配置Spring框架配置文件

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.imooc</groupId>
  <artifactId>Mybatis-Spring</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Mybatis-Spring Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://maven.apache.org</url>

  <properties>
    <junit.version>4.11</junit.version>
    <jsp.api.version>8.5.5</jsp.api.version>
    <jstl.version>1.2</jstl.version>
    <spring.version>4.1.6.RELEASE</spring.version>
    <aspectjweaver.version>1.8.5</aspectjweaver.version>
    <mybatis.version>3.2.8</mybatis.version>
    <mybatis.spring.version>1.2.2</mybatis.spring.version>
    <c3p0.version>0.9.5</c3p0.version>
    <mysql.version>5.1.35</mysql.version>
    <log4j.version>1.2.17</log4j.version>
    <json.version>2.4</json.version>
  </properties>


  <dependencies>
    <!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <!-- 该jar包保留到测试 -->
      <scope>test</scope>
    </dependency>
    <!-- jsp-api、servlet-api、el -->
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-jsp-api</artifactId>
      <version>${jsp.api.version}</version>
      <!-- 该jar包最终由Web容器提供 -->
      <scope>provided</scope>
    </dependency>

    <!-- jstl -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <!-- Spring4 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
      <exclusions>
        <exclusion>
          <artifactId>commons-logging</artifactId>
          <groupId>commons-logging</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>${aspectjweaver.version}</version>
    </dependency>
    <!-- mybatis3 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>
    <!-- c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>${c3p0.version}</version>
    </dependency>
    <!-- mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!-- log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <!-- json-lib -->
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>${json.version}</version>
      <!-- 指定jar包jdk版本的依赖 -->
      <classifier>jdk15</classifier>
      <exclusions>
        <exclusion>
          <artifactId>commons-lang</artifactId>
          <groupId>commons-lang</groupId>
        </exclusion>
      </exclusions>
    </dependency>

  </dependencies>

  <build>
    <finalName>Mybatis-Spring</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

ec_article商品表

ec_article_type商品类型表

ec_user用户表

创建实体类和映射文件

配置Spring框架配置文件

<?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:c="http://www.springframework.org/schema/c"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      				  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      				  http://www.springframework.org/schema/tx
      				  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
      				  http://www.springframework.org/schema/context
      				  http://www.springframework.org/schema/context/spring-context-4.0.xsd
      				  ">

    <!-- 声明用了annotation注解bean
           开启组件扫描:它会到基础包下扫描@Service @Repository @Controller @Component这四种注解声明的bean,
          扫描后会将这些bean交由Spring容器管理
    -->
    <context:component-scan base-package="com.imooc.shop"></context:component-scan>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"/>

    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="dataSource">
        <!-- 配置类型别名:采用包扫描的方式到基础包下扫描所有的类,作为MyBatis2能够转换的类型,多个包之间用;分隔 -->
        <property name="typeAliasesPackage">
            <value>
                com.imooc.shop.bean
            </value>
        </property>
    </bean>

    <!-- 配置数据访问接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:sqlSessionFactoryBeanName="sqlSessionFactory">
        <!-- 配置数据访问接口:采用包扫描的方式到基础包下扫描所有的类,作为MyBatis2的数据访问接口,
            并创建这些类的代理对象,创建出来后会把这些代理对象交给Spring容器管理,bean的id名默认为接口的类名前面首字母小写
           多个包之间用;分隔 -->
        <property name="basePackage">
            <value>
                com.imooc.shop.repository
            </value>
        </property>
    </bean>

    <!-- 配置DataSourceTransactionManager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
          p:dataSource-ref="dataSource"/>

    <!-- 开启annotation注解事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

c3p0.properties

架构串联测试

书写一个查询所有商品类型的Servlet类

在Servlet中注入业务层组件

调用业务层组件的方法

在业务层组件中注入Mybatis的持久层对象

在持久层对象中查询出所有商品类型数据返回

package com.imooc.shop.action;

import com.imooc.shop.bean.ArticleType;
import com.imooc.shop.service.ShopService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/getArticleTypes")
public class ArticleTypeServlet extends HttpServlet {
    //定义业务层对象
    private ShopService shopService;

    @Override
    public void init() throws ServletException {
        super.init();
        //获取Spring容器,然后从容器中得到业务层对象
        ServletContext servletContext =this.getServletContext();
        WebApplicationContext context =
                WebApplicationContextUtils.getWebApplicationContext(servletContext);
        shopService = (ShopService)context.getBean("shopService");


    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查询出所有的商品类型信息
        List<ArticleType> articleTypes = shopService.getArticleTypes();
        System.out.println(articleTypes);
    }
}

ShopService

package com.imooc.shop.service;


import com.imooc.shop.bean.ArticleType;

import java.util.List;

public interface ShopService {
    List<ArticleType> getArticleTypes();

}

shopServiceImpl

package com.imooc.shop.service;

import com.imooc.shop.bean.ArticleType;
import com.imooc.shop.repository.ArticleTypeMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("shopService")
public class ShopServiceImpl implements ShopService {
    //得到数据访问层对象
    @Resource
    private ArticleTypeMapper articleTypeMapper;

    @Override
    public List<ArticleType> getArticleTypes() {
        return articleTypeMapper.getArticleTypes();
    }
}

ArticleTypeMapper

package com.imooc.shop.repository;

import com.imooc.shop.bean.ArticleType;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface ArticleTypeMapper {

    @Select("select * from ec_article_type")
    List<ArticleType> getArticleTypes();
}

整合成功 

用户登录

导入界面架构

LoginServlet.java

package com.imooc.shop.action;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req,resp);
    }
}

index.jsp 

完成登录

LoginServlet

package com.imooc.shop.action;

import com.imooc.shop.bean.User;
import com.imooc.shop.service.ShopService;
import com.imooc.shop.utils.Constants;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private HttpServletRequest request;
    private HttpServletResponse response;
    //定义业务层对象
    private ShopService shopService;
    @Override
    public void init() throws ServletException {
        super.init();
        //获取spring的容器,然后从容器中得到业务层对象
        ServletContext servletContext = this.getServletContext();
        WebApplicationContext context =
                WebApplicationContextUtils.getWebApplicationContext(servletContext);
        shopService = (ShopService)context.getBean("shopService");

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.request=req;
        this.response=resp;
        String method = req.getParameter("method");
        switch (method) {
            case "getJsp":
                //跳转到登录界面
                req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
                break;
            case "login":
                login();
                break;
        }
    }

    private void login(){
        try {
            String loginName= request.getParameter("loginName");
            String passWord = request.getParameter("passWord");
            Map<String,Object> results = shopService.login(loginName,passWord);
            if((int)results.get("code")==0) {
                //登录成功的
                //把登录成功的用户注入到session会话中去
                //跳转到主页面
                User user = (User) results.get("msg");
                request.setAttribute(Constants.USER_SESSION,user);
                //请求跳转到主界面的servlet
                request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request,response);

            }else{
                String msg = results.get("msg")+"";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

ShopService

package com.imooc.shop.service;


import com.imooc.shop.bean.ArticleType;

import java.util.List;
import java.util.Map;

public interface ShopService {
    List<ArticleType> getArticleTypes();
    Map<String,Object> login(String loginName, String passWord);
}

ShopServiceImpl

package com.imooc.shop.service;

import com.imooc.shop.bean.ArticleType;
import com.imooc.shop.bean.User;
import com.imooc.shop.repository.ArticleTypeMapper;
import com.imooc.shop.repository.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("shopService")
public class ShopServiceImpl implements ShopService {
    //得到数据访问层对象
    @Resource
    private ArticleTypeMapper articleTypeMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public List<ArticleType> getArticleTypes() {
        return articleTypeMapper.getArticleTypes();
    }

    @Override
    public Map<String, Object> login(String loginName, String passWord) {
       Map<String,Object> results = new HashMap<>();
       //判断参数是否为空的
        if(StringUtils.isEmpty(loginName)||StringUtils.isEmpty(passWord)){
            //参数为空了
            results.put("code",1);
            results.put("msg","参数为空了");
        }else{
            //根据登录名称去查询用户对象
            User user =userMapper.login(loginName);
            System.out.println(user.getPassword());
            if(user !=null){
                //判断密码
                if(user.getPassword().equals(passWord)){
                    //登录成功了
                    //应该将登陆成功的用户存到Session会话中
                    results.put("code",0);
                    results.put("msg",user);

                }else{
                    //密码错误了
                    results.put("code",2);
                    results.put("msg","密码错误了");
                }
            }else{
                //登录名不存在
                results.put("code",3);
                results.put("msg","登录名不存在");
            }

        }
        return results;
    }
}

UserMapper 

package com.imooc.shop.repository;

import com.imooc.shop.bean.User;
import org.apache.ibatis.annotations.Select;


public interface UserMapper {

    @Select("select * from ec_user where login_name=#{xxx}")
    User login(String loginName);

}

util.Constants

package com.imooc.shop.utils;

public class Constants {
    public static final String USER_SESSION="user_session";
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值