您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

springmvc+mybatis的实例详解

2025/6/9 13:25:21发布10次查看
前面讲到:spring+springmvc+mybatis深入学习及搭建(十三)——springmvc入门程序(二)
1.需求使用springmvc和mybatis完成商品列表查询。
2.整合思路springmvc+mybatis的系统架构:
第一步:整合dao层
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
第二步:整合service层
通过spring管理service接口。
使用配置方式将service接口配置在spring配置文件中。
实现事务控制。
第三步:整合springmvc
由于springmvc是spring的模块,不需要整合。
3.环境准备数据库环境:mysql5.6
java环境:
jdk1.7
myeclipse2014
springmvc版本:spring3.2
所需要的jar包:
数据库驱动包
mybatis的jar包
mybatis的spring的整合包
log4j包
dbcp数据库连接池包
spring3.2所有jar包
jstl包
过程结构目录:
4.整合dao mybatis和spring进行整合。
4.1 db.propertiesjdbc.driver=com.mysql.jdbc.driver jdbc.url=jdbc:mysql://localhost:3306/mybatisdemo jdbc.username=root jdbc.password=
4.2 log4j.properties# global logging configuration,建议开发环境要用debug log4j.rootlogger=debug, stdout # console output... log4j.appender.stdout=org.apache.log4j.consoleappender log4j.appender.stdout.layout=org.apache.log4j.patternlayout log4j.appender.stdout.layout.conversionpattern=%5p [%t] - %m%n
4.3 sqlmapconfig.xml在classpath下创建mybatis/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="joanna.yan.ssm.po"/></typealiases><!-- 配置mapper 由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。 但是必须遵循:mapper.xml和mapper.java文件同名且在一个目录 --><!-- <mappers></mappers> -->  </configuration>
4.4 applicationcontext-dao.xml在classpath下创建spring/applicationcontext-dao.xml。配置:数据源、事务管理、sqlsessionfactory、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 "><!-- 加载db.properties文件中的内容,db.properties文件中的key命名要有一定的特殊规则 --><context:property-placeholder location="classpath:db.properties"/><!-- 配置数据源,dbcp --><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><!-- sqlsessinfactory --><bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"><!-- 加载mybatis的全局配置文件 --><property name="configlocation" value="classpath:mybatis/sqlmapconfig.xml" /><!-- 数据库连接池 --><property name="datasource" ref="datasource" /></bean><!-- mapper扫描器 --><bean class="org.mybatis.spring.mapper.mapperscannerconfigurer"><!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 --><property name="basepackage" value="joanna.yan.ssm.mapper"/><property name="sqlsessionfactorybeanname" value="sqlsessionfactory"/></bean></beans>
4.5逆向工程生成po类及mapper(即单表增删改查)详情见:spring+springmvc+mybatis深入学习及搭建(十)——mybatis逆向工程
将生成的文件拷贝至工程中。
4.6手动定义商品查询mapper针对综合查询mapper,一般情况会有关联查询,建议自定义mapper。
4.6.1 itemsmappercustom.xmlsql语句:
         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="joanna.yan.ssm.mapper.itemsmappercustom" ><!-- 定义商品查询的sql片段,就是商品查询条件 --><sql id="query_items_where"><!-- 使用动态sql,通过if判断,满足条件进行sql拼接 --><!-- 商品查询条件通过itemsqueryvo包装对象中itemscustom属性传递 --><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="joanna.yan.ssm.po.itemsqueryvo" resulttype="joanna.yan.ssm.po.itemscustom">select items.* from items<where><include refid="query_items_where"></include></where></select></mapper>
4.6.2 itemsmappercustom.javapublic interface itemsmappercustom {//商品查询列表public list<itemscustom> finditemslist(itemsqueryvo itemsqueryvo) throws exception; }
5.整合service让spring管理service接口。
5.1定义service接口package joanna.yan.ssm.service;import java.util.list;import joanna.yan.ssm.po.itemscustom;import joanna.yan.ssm.po.itemsqueryvo;public interface itemsservice {//商品查询列表public list<itemscustom> finditemslist(itemsqueryvo itemsqueryvo) throws exception; }
package joanna.yan.ssm.service.impl;import java.util.list;import org.springframework.beans.factory.annotation.autowired;import joanna.yan.ssm.mapper.itemsmappercustom;import joanna.yan.ssm.po.itemscustom;import joanna.yan.ssm.po.itemsqueryvo;import joanna.yan.ssm.service.itemsservice;public class itemsserviceimpl implements itemsservice{          @autowiredprivate itemsmappercustom itemsmappercustom;     @overridepublic list<itemscustom> finditemslist(itemsqueryvo itemsqueryvo)throws exception {//通过itemsmappercustom查询数据库return itemsmappercustom.finditemslist(itemsqueryvo);     } }
5.2在spring容器配置service(applicationcontext-service.xml) 在classpath下创建spring/applicationcontext-service.xml,文件中配置service。
<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 "><!-- 商品管理的service --><bean id="itemsservice" class="joanna.yan.ssm.service.impl.itemsserviceimpl"/></beans>
5.3事务控制(applicationcontext-transaction.xml)在classpath下创建spring/applicationcontext-service.xml,文件中使用spring声明式事务控制方法。
<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 "><!-- 事务管理器 对mybatis操作数据库事务控制,spring使用jdbc的事务控制类 --><bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager"><!-- 数据源 datasource在applicationcontext-dao.xml中配置了 --><property name="datasource" ref="datasource"/>    </bean><!-- 通知 --><tx:advice id="txadvice" transaction-manager="transactionmanager"><tx:attributes><!-- 传播行为 --><!-- 可以变相的规范程序员的命名,例如以save开头,update开头等,不能想怎么命名就怎么命名 --><tx:method name="save*" propagation="required"/><!-- 要求 --><tx:method name="delete*" propagation="required"/><tx:method name="update*" propagation="required"/><tx:method name="insert*" 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 --><aop:config><!-- 切入点为joanna.yan.ssm.service.impl包下所有类的所有方法,不管里面什么参数 --><aop:advisor advice-ref="txadvice" pointcut="execution(* joanna.yan.ssm.service.impl.*.*(..))"/></aop:config></beans>
6.整合springmvc 6.1 springmvc.xml在classpath下创建spring/springvc.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 "><!-- 可以扫描controller、service、... 这里让扫描controller,指定controller的包 --><context:component-scan base-package="joanna.yan.ssm.controller"></context:component-scan><!--注解映射器 --><!-- <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><!-- 配置视图解析器 解析jsp视图,默认使用jstl标签,所有classpath下得有jstl的包--><bean class="org.springframework.web.servlet.view.internalresourceviewresolver"><!--配置jsp路径的前缀 --><property name="prefix" value="/web-inf/jsp/"/><!--配置jsp路径的后缀 --><property name="suffix" value=".jsp"/></bean></beans>
6.2配置前端控制器参考入门程序:spring+springmvc+mybatis深入学习及搭建(十二)——springmvc入门程序(一)
在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 " id="webapp_id" version="3.0">   <display-name>springmvc_mybatis</display-name>   <welcome-file-list><welcome-file>index.jsp</welcome-file>   </welcome-file-list>   <!-- springmvc前端控制器 -->   <servlet>  <servlet-name>springmvc</servlet-name>  <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>  <!-- contextconfiglocation配置springmvc加载的配置文件(该配置文件中配置了处理器映射器、适配器等等) 如果不配置contextconfiglocation,默认加载的是/web-inf/servlet名称-servlet.xml(即springmvc-servlet.xml) -->  <init-param>  <param-name>contextconfiglocation</param-name>  <param-value>classpath:spring/springmvc.xml</param-value>  </init-param>  <!-- 表示servlet随服务启动 -->  <load-on-startup>1</load-on-startup>   </servlet>      <servlet-mapping>  <servlet-name>springmvc</servlet-name>  <!--servlet拦截方式 方式一:*.action,访问以.action结尾由dispatcherservlet进行解析 方式二:/,所有访问的地址都由dispatcherservlet进行解析,对于静态文件的解析需要配置不让dispatcherservlet进行解析。 使用此方式可以实现restful风格的url 方式三:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时, 仍然会由dispatcherservlet解析jsp地址,不能根据jsp页面找到handler,会报错-->  <url-pattern>*.action</url-pattern>   </servlet-mapping>   </web-app>
6.3编写controller(就是handler)@controllerpublic class itemscontroller {          @autowiredprivate itemsservice itemsservice;//商品查询http://localhost:8080/springmvc_mybatis/queryitems.action@requestmapping(/queryitems)public modelandview queryitems() throws exception{//调用service查找数据库,查询商品列表list<itemscustom> itemslist=itemsservice.finditemslist(null);        //返回modelandviewmodelandview modelandview=new modelandview();         modelandview.addobject(itemslist, itemslist);//指定视图//        modelandview.setviewname(/web-inf/jsp/items/itemslist.jsp);//下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为modelandview.setviewname(items/itemslist);return modelandview;     } }
6.4编写jsp
<%@ page language="java" contenttype="text/html; charset=utf-8"pageencoding="utf-8"%><%@ taglib uri="" prefix="c" %><%@ taglib uri="" 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>
7.加载spring容器将mapper、service、controller加载到spring容器中。
建议使用通配符加载上边的配置文件。
在web.xml中添加spring容器监听器,加载spring容器。
  <!-- 加载spring容器 -->   <context-param>  <param-name>contextconfiglocation</param-name>  <param-value>/web-inf/classes/spring/applicationcontext-*.xml</param-value>   </context-param>   <listener>  <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>   </listener>
8.商品查询调试访问地址:http://localhost:8080/springmvc_mybatis/queryitems.action
查询结果:
以上就是springmvc+mybatis的实例详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product