欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringMVC mybatis整合实例代码详解

程序员文章站 2024-02-28 20:22:10
mybatis 本是apache的一个开源项目ibatis, 2010年这个项目由apache software foundation 迁移到了google code,并且...

mybatis 本是apache的一个开源项目ibatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为mybatis 。

一、逆向工程生成基础信息

<?xml version="1.0" encoding="utf-8"?>
<!doctype generatorconfiguration
public "-//mybatis.org//dtd mybatis generator configuration 1.0//en"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorconfiguration>
<context id="testtables" targetruntime="mybatis3">
<commentgenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressallcomments" value="true" />
</commentgenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcconnection driverclass="com.mysql.jdbc.driver"
connectionurl="jdbc:mysql://localhost:3307/mybatis" userid="root"
passaspku.com/pc/softtech/office/word/" target="_blank"><u>word</u>="jalja">
</jdbcconnection>
<!-- 默认false,把jdbc decimal 和 numeric 类型解析为 integer,为 true时把jdbc decimal 和 
numeric 类型解析为java.math.bigdecimal -->
<javatyperesolver>
<property name="forcebigdecimals" value="false" />
</javatyperesolver>
<!-- targetproject:生成po类的位置 -->
<javamodelgenerator targetpackage="com.jalja.springmvc_mybatis.model.pojo"
targetproject=".\src">
<!-- enablesubpackages:是否让schema作为包的后缀 -->
<property name="enablesubpackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimstrings" value="true" />
</javamodelgenerator>
<!-- targetproject:mapper映射文件生成的位置 -->
<sqlmapgenerator targetpackage="com.jalja.springmvc_mybatis.mapper"
targetproject=".\src">
<!-- enablesubpackages:是否让schema作为包的后缀 -->
<property name="enablesubpackages" value="false" />
</sqlmapgenerator>
<!-- targetpackage:mapper接口生成的位置 -->
<javaclientgenerator type="xmlmapper"
targetpackage="com.jalja.springmvc_mybatis.mapper"
targetproject=".\src">
<!-- enablesubpackages:是否让schema作为包的后缀 -->
<property name="enablesubpackages" value="false" />
</javaclientgenerator>
<!-- 指定数据库表 -->
<table tablename="items"></table>
<table tablename="orders"></table>
<table tablename="orderdetail"></table>
<table tablename="user"></table>
</context>
</generatorconfiguration> 
public static void main(string[] arhs) throws exception{
list<string> warnings = new arraylist<string>();
boolean overwrite = true;
file configfile = new file("src.main.resources/generator.xml");
configurationparser cp = new configurationparser(warnings);
configuration config = cp.parseconfiguration(configfile);
defaultshellcallback callback = new defaultshellcallback(overwrite);
mybatisgenerator mybatisgenerator = new mybatisgenerator(config, callback, warnings);
mybatisgenerator.generate(null);
}

二、springmvc与mybatis整合 各个配置文件

1.项目结构

2、各个文件的核心代码

a.web.xml

<?xml version="1.0" encoding="utf-8"?> 
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> 
<welcome-file-list> 
<welcome-file>index.jsp</welcome-file> 
</welcome-file-list> 
<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> 
<context-param> 
<param-name>log4jconfiglocation</param-name> 
<param-value>classpath:log4j.properties</param-value> 
</context-param> 
<context-param> 
<param-name>log4jrefreshinterval</param-name> 
<param-value>3000</param-value> 
</context-param> 
<listener> 
<listener-class>org.springframework.web.util.log4jconfiglistener</listener-class> 
</listener> 
<!-- post请求乱码 -->
<filter>
<filter-name>springencodingfilter</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>springencodingfilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping> 
<!-- springmvc前端控制器 --> 
<servlet> 
<servlet-name>springmvc</servlet-name> 
<servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> 
<init-param> 
<!-- 
contextconfiglocation加载 springmvc的配置文件(处理器适配器 ,映射器) 
如果不配置默认加载的是 /web-inf/servlet名称-servlet.xml(springmvc-servlet.xml)
-->
<param-name>contextconfiglocation</param-name> 
<param-value>classpath:spring/springmvc.xml</param-value> 
</init-param> 
<load-on-startup>1</load-on-startup> 
</servlet> 
<servlet-mapping> 
<servlet-name>springmvc</servlet-name> 
<!--
1、*.do :dispatcherservlet 解析所有 *.do 结尾的访问
2、 / :dispatcherservlet解析所有请求(包括静态资源) 这种配置可以实现restful风格的url
3、/*: 这种配置最终要转发到一个jsp页面 
-->
<url-pattern>*.do</url-pattern> 
</servlet-mapping> 
<!-- springmvc前端控制器 restful 
<servlet> 
<servlet-name>springmvc_rest</servlet-name> 
<servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> 
<init-param> 
<param-name>contextconfiglocation</param-name> 
<param-value>classpath:spring/applicationcontext-springmvc.xml</param-value> 
</init-param> 
<load-on-startup>1</load-on-startup> 
</servlet> 
<servlet-mapping> 
<servlet-name>springmvc_rest</servlet-name> 
<url-pattern>/</url-pattern> 
</servlet-mapping> 
-->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>

b、config/mybatis/applicationcontext-mybatis.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> 
<!-- 
各个属性
properties:
setting(全局配置参数配置):mybatis运行时可以调整一些运行参数 例如:开启二级缓存、开启延迟加载 
typealiases(类型别名): 在mapper.xml中定义parametertype 参数类型 resulttype 返回类型时 
需要指定类型的路径 不方便开发,我们开一针对 这些类型给其指定别名
typehandler(类型处理器):在mybatis 中是通过typehandler 完成 jdbc类型与java类型的转化 ,mybatis 提供的处理器已可满足 开发需求 
objectfactory(对象工厂):
plugins(插件):
environments(环境集合属性对象):
environment(环境子属性对象):
transactionmanager(事务管理):
datasource(数据源):
mappers(映射器): 
-->
<!-- 对事务的管理和连接池的配置 --> 
<!-- 延迟加载 -->
<settings>
<!-- 打开延迟加载 -->
<setting name="lazyloadingenabled" value="true"/>
<!-- 积极加载改为消极加载 -->
<setting name="aggressivelazyloading" value="false"/>
<!-- 开启二级缓存 -->
<setting name="cacheenabled" value="true"/>
</settings>
<typealiases>
<!-- 针对单个别名定义 -->
<!-- <typealias type="com.jalja.mybatis.model.user" alias="user"/> -->
<!--批量别名的定义 mybatis 自动扫描包中的类 别名就是类名(首字母大小写都可以) -->
<package name="com.jalja.springmvc_mybatis.model.pojo"/>
<package name="com.jalja.springmvc_mybatis.model.custom"/>
<package name="com.jalja.springmvc_mybatis.model.vo"/>
</typealiases>
<!--加载映射文件 -->
<!-- <mappers> <mapper resource="com/jalja/spring_mybatis/mapper/usermapper.xml"/> -->
<!-- 和spring整合后 可以去掉 
<package name="com.jalja.spring_mybatis.mapper"/> </mappers>-->
</configuration>

c、config/spring/applicationcontext-dao.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-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/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/cache 
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
<!-- 引入jdbc配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/> 
<!-- 对jdbc配置进行解密 
<bean id="propertyconfigurer" class="cn.com.sinobpo.project.wfjb.utils.encryptablepropertyplaceholderconfigurer"> 
<property name="locations">
<list>
<value>classpath:resources/config/jdbc.properties</value>
</list>
</property>
</bean> -->
<bean id="datasource" class="org.apache.commons.dbcp.basicdatasource" destroy-method="close">
<property name="driverclassname">
<value>${jdbc_driverclassname}</value>
</property>
<property name="url">
<value>${jdbc_url}</value>
</property>
<property name="username">
<value>${jdbc_username}</value>
</property>
<property name="password">
<value>${jdbc_password}</value>
</property>
<!-- 连接池最大使用连接数 -->
<property name="maxactive">
<value>20</value>
</property>
<!-- 初始化连接大小 -->
<property name="initialsize">
<value>1</value>
</property>
<!-- 获取连接最大等待时间 -->
<property name="maxwait">
<value>60000</value>
</property>
<!-- 连接池最大空闲 -->
<property name="maxidle">
<value>20</value>
</property>
<!-- 连接池最小空闲 -->
<property name="minidle">
<value>3</value>
</property>
<!-- 自动清除无用连接 -->
<property name="removeabandoned">
<value>true</value>
</property>
<!-- 清除无用连接的等待时间 -->
<property name="removeabandonedtimeout">
<value>180</value>
</property>
<!-- 连接属性 -->
<property name="connectionproperties">
<value>clientencoding=utf-8</value>
</property>
</bean>
<!-- spring和mybatis完美整合 --> 
<bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"> 
<property name="datasource" ref="datasource"/> 
<property name="configlocation" value="classpath:mybatis/applicationcontext-mybatis.xml"/>
</bean> 
<!--使用 mapper 代理 的方式 mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.mapperscannerconfigurer"> 
<!-- 扫描包路径 如果需要扫描多个包 ,中间使用半角逗号隔开 -->
<property name="basepackage" value="com.jalja.springmvc_mybatis.mapper"/> 
<property name="sqlsessionfactorybeanname" value="sqlsessionfactory"/> 
</bean> 
<!--声明式 事务管理 使用jdbc的事务管理 -->
<bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
<property name="datasource" ref="datasource"></property>
</bean>
<!-- 配置事务通知-->
<tx:advice id="txadvice" transaction-manager="transactionmanager">
<tx:attributes>
<tx:method name="update*" propagation="required"/>
<tx:method name="save*" propagation="required"/>
<tx:method name="delete*" propagation="required"/>
<tx:method name="get*" propagation="supports" read-only="true"/> 
<tx:method name="find*" propagation="supports" read-only="true"/> 
</tx:attributes>
</tx:advice>
<!-- 配置事务的切点,并把事务切点和事务属性不关联起来aop -->
<aop:config>
<aop:advisor advice-ref="txadvice" pointcut="execution(* com.jalja.springmvc_mybatis.service.impl.*.*(..))"/>
</aop:config>
</beans>

d、config/spring/applicationcontext-service.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-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/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/cache 
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
<bean id="itemsservice" class="com.jalja.springmvc_mybatis.service.impl.itemsserviceimpl"></bean>
</beans>

e、config/spring/springmvc.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/cache 
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
<!--注解 处理器 映射器 -->
<!-- 映射器 org.springframework.web.servlet.mvc.annotation.defaultannotationhandlermapping springmvc3.1以前--> 
<!-- 映射器 org.springframework.web.servlet.mvc.method.annotation.requestmappinghandlermapping springmvc3.1以后 -->
<!-- 适配器 org.springframework.web.servlet.mvc.annotation.annotationmethodhandleradapter springmvc3.1以前--> 
<!-- 适配器 org.springframework.web.servlet.mvc.method.annotation.requestmappinghandleradapter springmvc3.1以后 -->
<!--配置映射器和 适配器 
<bean class="org.springframework.web.servlet.mvc.method.annotation.requestmappinghandlermapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.requestmappinghandleradapter"/> -->
<!-- 开启注解 映射器和 适配器 这种方式默认加载了很多参数绑定的方法 例如 json转换解析器-->
<mvc:annotation-driven/>
<!-- 配置 handler
<bean class="com.jalja.springmvc_mybatis.controller.usercontroller"/>-->
<!-- 注解 配置 基于组建扫描的方式 -->
<context:component-scan base-package="com.jalja.springmvc_mybatis.controller" />
<!-- 配置自定义参数解析器 -->
<mvc:annotation-driven conversion-service="conversionservice"/>
<bean id="conversionservice" class="org.springframework.format.support.formattingconversionservicefactorybean">
<property name="converters">
<list>
<!-- 日期类型转换 -->
<bean class="com.jalja.springmvc_mybatis.converter.customdateconverter"></bean>
</list>
</property>
</bean>
<!-- 全局异常处理器 -->
<bean class="com.jalja.springmvc_mybatis.exception.customexceptionresolver"/>
<!-- 文件上传 -->
<!-- 支持上传文件 --> 
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver">
<!-- 文件大小 5m -->
<property name="maxuploadsize" value="5242880"/>
</bean> 
<!-- 使用 restful 风格 编程 照成 的 静态资源 访问 问题 -->
<!-- <mvc:resources mapping="/js/**" location="/resources/js/"/> -->
<!-- springmvc拦截器的配置 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.jalja.springmvc_mybatis.interceptor.logininterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<!-- 视图映射 jsp解析 默认使用jstl-->
<bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
<!-- 默认使用 -->
<property name="viewclass" value="org.springframework.web.servlet.view.jstlview"/>
<property name="prefix" value="/web-inf/jsp/" />
<property name="suffix" value=".jsp" />
</bean> 
</beans>

f、config/jdbc.properties

jdbc_driverclassname=com.mysql.jdbc.driver
jdbc_url=jdbc:mysql://localhost:3306/mybatis?useunicode=true&characterencoding=utf-8
jdbc_username=root
jdbc_password=111111

g、config/log4j.properties

#在开发环境下的日志级别 要设置成debug,生成环境设置成info 或error
log4j.rootlogger=debug, stdout
log4j.logger.org.apache.ibatis=debug
log4j.appender.stdout=org.apache.log4j.consoleappender
log4j.appender.stdout.layout=org.apache.log4j.patternlayout
log4j.appender.stdout.layout.conversionpattern=%5p [%t] - %m%n

h、com/jalja/springmvc_mybatis/controller/itemscontroller.java

package com.jalja.springmvc_mybatis.controller;
import java.io.file;
import java.util.list;
import java.util.uuid;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.multipart.multipartfile;
import com.jalja.springmvc_mybatis.exception.customexception;
import com.jalja.springmvc_mybatis.model.custom.itemscustom;
import com.jalja.springmvc_mybatis.service.itemsservice;
/**
* 商品 
* @author pc003
*conterver参数转换器 springmvc提供了很多参数转换器
*/
@controller
@requestmapping("/items") //窄化请求映射
public class itemscontroller {
@autowired itemsservice itemsservice;
@requestmapping(value="/finditemslist")
public string finditemslist(model model) throws exception{
list<itemscustom> itemslist=itemsservice.finditemslist(null);
system.out.println(itemslist);
model.addattribute("itemslist", itemslist);
return "itemslist";
}
@requestmapping(value="/edititems", method={requestmethod.post,requestmethod.get}) //限制http请求方式
//@requestparam 将请求参数 与 形式参数进行绑定 required:指定属性必须传入值 defaultvalue:设置默认值
public string edititems(model model, @requestparam(value="id",required=true,defaultvalue="0") integer itemsid) throws exception{
itemscustom itemscustom=itemsservice.finditemsbyid(itemsid);
if(itemscustom==null){
throw new customexception("商品不存在");
}
model.addattribute("itemscustom", itemscustom);
return "edititems";
}
@requestmapping(value="/updateitems")
public string edititemssubmit(integer id,itemscustom itemscustom,multipartfile itemspic) throws exception{
string uploadfilename=itemspic.getoriginalfilename();//获取上传的文件名
if(itemspic!=null && uploadfilename!=null && !uploadfilename.equals("")){
string imagespath="e:\\develop\\upload\\images\\";
string newfilename=uuid.randomuuid()+uploadfilename.substring(uploadfilename.lastindexof("."),uploadfilename.length());
file newfile=new file(imagespath+newfilename);
itemspic.transferto(newfile);//将内存中的数据写入磁盘
itemscustom.setpic(newfilename);
}
itemsservice.updateitemsbyid(id, itemscustom);
return "redirect:finditemslist.do"; //重定向
}
//json的使用 @responsebody:将对像转json输出 @requestbody:将请求参数转 java对象
@requestmapping(value="/jsonrequest")
public @responsebody itemscustom jsonrequest(@requestbody itemscustom itemscustom) throws exception{
return itemscustom;
}
//restful 风格 编程 /restfulrequest/{id}:表示将这个位置的参数传到 @pathvariable 指定的名称中
@requestmapping(value="/restfulrequest/{id}")
public @responsebody itemscustom restfulrequest(@pathvariable("id") integer id) throws exception{
itemscustom itemscustom=itemsservice.finditemsbyid(id);
return itemscustom;
}
}

希望本篇实例对您有所帮助