springmvc和mybatis整合
Posted soldierback
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springmvc和mybatis整合相关的知识,希望对你有一定的参考价值。
一、需求
使用springmvc和mybatis完成商品列表查询
二、整合思路
springmvc+mybaits的系统架构:
第一步:整合dao层
mybatis和spring整合,通过spring管理mapper接口;
使用mapper的扫描器自动扫描mapper接口在spring中进行注册
第二步:整合service层
通过spring管理 service接口;
使用配置方式将service接口配置在spring配置文件中;
实现事务控制
第三步:整合springmvc
由于springmvc是spring的模块,不需要整合
三、环境准备
(1)数据库环境:mysql 5.7.25
(2)数据库的系统环境:ubuntu 18.04.2
(3)Java环境:JDK1.8.0_201;eclipse 2019-03
(4)springmvc版本:4.0.0.RELEASE
(5)所需要的jar包:数据库驱动包:mysql 5.1;
mybatis的jar包;
mybatis和spring整合包;
log4j包;
dbcp数据库连接池包;
spring 4.0 所有jar包;jstl包
(6)相关jar包提取
链接: https://pan.baidu.com/s/1LreOdB83aKkFnu0RK8TVuQ
提取码: vuq3
四、工程结构
五、整合dao
5.1 sqlMapConfig.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> <!-- 全局setting配置,根据需要添加 --> <!-- 别名配置 --> <typeAliases> <!-- 批量扫描别名 --> <package name="com.chuanye.ssm.pojo" /> </typeAliases> <!-- 使用自动扫描器时,mapper.xml文件如果和mapper.java接口 在一个目录则此处不用定义mappers --> <!-- <mappers> <package name="com.chuanye.ssm.mapper" /> </mappers> --> </configuration>
5.2 applicationContext-dao.xml
配置:1)数据源;2)SqlSessionFactory;3)mapper扫描器
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 加载配置文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 数据库连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="30" /> <property name="maxIdle" value="5" /> </bean> <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的全局配置文件 --> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /> </bean> <!-- mapper扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.chuanye.ssm.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> </beans>
5.3 逆向工程生成po类及mapper
参考:https://www.cnblogs.com/soldierback/p/10606251.html
将生成的文件拷贝至工程 中
5.4 手动定义商品查询mapper
(针对综合查询mapper,一般情况会有关联查询,建议自定义mapper)
1)ItemsMapperCustom.xml
sql语句:SELECT * FROM items WHERE items.name LIKE ‘%笔记本%‘
<?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="com.chuanye.ssm.mapper.ItemsMapperCustom"> <!-- 定义商品查询的sql片段,就是商品查询条件 --> <sql id="query_items_where"> <!-- 使用动态sql,通过if判断,满足条件进行sql拼接 --> <if test="itemsCustom != null"> <if test="itemsCustom.name != null and itemsCustom.name != ‘‘"> items.name LIKE ‘${itemsCustom.name}%‘ </if> </if> </sql> <!-- 商品列表查询 --> <!-- parameterType传入包装对象(包装了查询条件) resultType建议使用扩展对象 --> <select id="findItemsList" parameterType="com.chuanye.ssm.pojo.ItemsQueryVo" resultType="com.chuanye.ssm.pojo.ItemsCustom"> SELECT items.* FROM items <where> <include refid="query_items_where"></include> </where> </select> </mapper>
2)ItemsMapperCustom.java
package com.chuanye.ssm.mapper; import java.util.List; import com.chuanye.ssm.pojo.ItemsQueryVo; public interface ItemsMapperCustom { // 商品查询列表 public List<ItemsMapperCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception; }
3)ItemsCustom.java
package com.chuanye.ssm.pojo; /** * <p>Title: ItemsCustom</p> * <p>Description: 商品信息扩展类</p> * <p>Copyright: Copyright (c) 2019</p> * <p>Company: chuanye</p> * @author freebird * @version Mar 29, 20191:33:55 PM */ public class ItemsCustom extends Items { // 添加商品信息的扩展属性 }
4)ItemsQueryVo
package com.chuanye.ssm.pojo; /** * <p>Title: ItemsQueryVo</p> * <p>Description: 商品包装对象</p> * <p>Copyright: Copyright (c) 2019</p> * <p>Company: chuanye</p> * @author freebird * @version Mar 29, 20191:32:07 PM */ public class ItemsQueryVo { // 商品信息 private Items items; // 为了系统可扩展性,对原始生成的pojo进行扩展 private ItemsCustom itemsCustom; public Items getItems() { return items; } public void setItems(Items items) { this.items = items; } public ItemsCustom getItemsCustom() { return itemsCustom; } public void setItemsCustom(ItemsCustom itemsCustom) { this.itemsCustom = itemsCustom; } }
六、整合service(让spring管理service接口)
6.1 定义service接口
package com.chuanye.ssm.service; import java.util.List; import com.chuanye.ssm.pojo.ItemsCustom; import com.chuanye.ssm.pojo.ItemsQueryVo; /** * <p>Title: ItemsSerevice</p> * <p>Description: 商品管理service接口</p> * <p>Copyright: Copyright (c) 2019</p> * <p>Company: chuanye</p> * @author freebird * @version Mar 29, 20192:02:22 PM */ public interface ItemsSerevice { // 商品查询列表 public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception; }
package com.chuanye.ssm.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.chuanye.ssm.mapper.ItemsMapperCustom; import com.chuanye.ssm.pojo.ItemsCustom; import com.chuanye.ssm.pojo.ItemsQueryVo; import com.chuanye.ssm.service.ItemsSerevice; /** * <p>Title: ItemsServiceImpl</p> * <p>Description: 商品管理service实现</p> * <p>Copyright: Copyright (c) 2019</p> * <p>Company: chuanye</p> * @author freebird * @version Mar 29, 20192:05:28 PM */ public class ItemsServiceImpl implements ItemsSerevice { @Autowired private ItemsMapperCustom ItemsMapperCustom; @Override public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception { // TODO Auto-generated method stub return ItemsMapperCustom.findItemsList(itemsQueryVo); } }
6.2 在spring容器配置service(applicationContext-service.xml)
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 商品管理service --> <bean id="itemsService" class="com.chuanye.ssm.service.impl.ItemsServiceImpl"> </bean> </beans>
6.3 事务控制(applicationContext-transaction.xml)
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 事务管理器,对mybatis操作数据库事务控制,spring使用jdbc的事务控制类 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 数据源 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 传播行为 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- 切面 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.chuanye.ssm.service.impl.*.*(..))" /> </aop:config> </beans>
七、整合springmvc(创建springmvc.xml文件,配置处理器映射器、适配器、视图解析器)
7.1 springmvc.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- 扫描controller包 --> <context:component-scan base-package="com.chuanye.ssm.controller" /> <!-- 《注解映射器》 --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> <!-- 《注解适配器》 --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --> <!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置 mvc:annotation-driven默认加载很多的参数绑定方法,比如json转换 解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的 RequestMappingHandlerMapping和RequestMappingHandlerAdapter 实际开发时使用mvc:annotation-driven --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 《视图解析器》 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <!-- 配置jsp路径的前缀 --> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 配置jsp路径的后缀 --> <property name="suffix" value=".jsp"/> </bean> </beans>
7.2 配置前端控制器并加载spring容器(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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc_mybatis</display-name> <!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springmvc前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation配置springmvc加载的配置 文件(配置处理器映射器、适配器等等) 如果不 配置contextConfigLocation, 默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- 第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析; 第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不 让DispatcherServlet进行解析 使用此种方式可以实现 RESTful风格的url; 第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时, 仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错 --> <url-pattern>*.action</url-pattern> </servlet-mapping> </web-app>
7.3 编写controller
package com.chuanye.ssm.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.chuanye.ssm.pojo.ItemsCustom; import com.chuanye.ssm.service.ItemsSerevice; /** * <p>Title: ItemsController</p> * <p>Description: 商品管理Controller</p> * <p>Copyright: Copyright (c) 2019</p> * <p>Company: chuanye</p> * @author freebird * @version Mar 29, 20192:43:23 PM */ @Controller public class ItemsController { @Autowired private ItemsSerevice itemsSerevice; // 商品查询 @RequestMapping("/queryItems") public ModelAndView queryItems() throws Exception { // 调用service查找 数据库,查询商品列表 List<ItemsCustom> itemsList = itemsSerevice.findItemsList(null); // 返回ModelAndView ModelAndView modelAndView = new ModelAndView(); // 相当 于request的setAttribut,在jsp页面中通过itemsList取数据 modelAndView.addObject("itemsList", itemsList); // 指定视图 // 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为 // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp"); // 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀 modelAndView.setViewName("items/itemsList"); return modelAndView; } }
7.4 编写jsp(itemsList.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!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"> <title>查询商品列表</title> </head> <body> <form action="${pageContext.request.contextPath}/item/queryItem.action" method="post"> 查询条件: <table width="100%" border=1> <tr> <td><input type="submit" value="查询" /></td> </tr> </table> 商品列表: <table width="100%" border=1> <tr> <td>商品名称</td> <td>商品价格</td> <td>生产日期</td> <td>商品描述</td> <td>操作</td> </tr> <c:forEach items="${itemsList }" var="item"> <tr> <td>${item.name}</td> <td>${item.price}</td> <td> <fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/> </td> <td>${item.detail}</td> <td> <a href="${pageContext.request.contextPath}/item/editItem.action?id=${item.id}"> 修改 </a> </td> </tr> </c:forEach> </table> </form> </body> </html>
八、运行测试
九、项目目录
‘
以上是关于springmvc和mybatis整合的主要内容,如果未能解决你的问题,请参考以下文章
SpringMVC学习--springmvc和mybatis整合
shiro整合SSM(spring_springmvc_mybatis)