Java环境中MyBatis与Spring或Spring MVC框架的集成方法
与spring3集成
spring作为基础框架,可以集成后端框架,如hibernate,mybatis等。
前面是介绍单独使用mybatis的,大致逻辑是:
sqlsessionfactory <- configuration file (包括数据库连接配置)
ixxxmapper <- sqlsession <- sqlsessionfactory
<- mapper interface <- mapper xml
得到ixxmapper后,就可以调用其方法进行数据交互了。
和spring集成时,上面的这些对象需要作为bean来管理:
datasource bean <- 数据库连接配置
sqlsessionfactory bean <- datasource
<- configuration file
usermapper bean <- sqlsessionfactory
<- mapper interface
1. 在pom.xml中加入依赖:
<properties> <mybatis.spring.version>1.2.1</mybatis.spring.version> <dbcp.version>1.4</dbcp.version> <spring.version>3.1.2.release</spring.version> </properties> <dependencies> <dependency><!-- mybatis的几个对象包装成spring的bean --> <groupid>org.mybatis</groupid> <artifactid>mybatis-spring</artifactid> <version>${mybatis.spring.version}</version> </dependency> <dependency><!-- spring上下文用spring-jdbc连接数据库 --> <groupid>org.springframework</groupid> <artifactid>spring-jdbc</artifactid> <version>${spring.version}</version> </dependency> <dependency><!-- datasource是basicdatasource的实例 --> <groupid>commons-dbcp</groupid> <artifactid>commons-dbcp</artifactid> <version>${dbcp.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-test</artifactid> <version>${spring.version}</version> </dependency> </dependencies>
2. 在类路径下创建beans-da.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" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="datasource" class="org.apache.commons.dbcp.basicdatasource"><!-- 数据库连接bean --> <property name="driverclassname" value="com.mysql.jdbc.driver" /> <property name="url" value="jdbc:mysql://localhost:3306/hbatis?characterencoding=utf8" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"><!-- sqlsessionfactory bean --> <property name="datasource" ref="datasource" /><!-- 数据源 --> <property name="configlocation" value="classpath:configuration.xml" /><!-- 配置文件 --> </bean> <bean id="usermapper" class="org.mybatis.spring.mapper.mapperfactorybean"><!-- user映射bean--> <property name="sqlsessionfactory" ref="sqlsessionfactory" /> <property name="mapperinterface" value="com.john.hbatis.mapper.iusermapper" /><!-- 映射接口 --> </bean> </beans>
3. 测试类:
@contextconfiguration(locations = { "classpath:beans-da.xml" }) public class springintegrationtest extends abstracttestngspringcontexttests { private static final logger log = loggerfactory.getlogger(springintegrationtest.class); @resource iusermapper mapper; @test public void querytest() { user user = mapper.getuserbyid(1); log.info("name: {}, address: {}", user.getname(), user.getaddress()); } }
与springmvc集成
这里我们建立在与spring3集成基础上来讲:
1. 往pom.xml添加springmvc和freemarker依赖:
<properties> <freemarker.version>2.3.19</freemarker.version> <servlet.version>2.5</servlet.version> </properties> <dependency> <groupid>org.freemarker</groupid> <artifactid>freemarker</artifactid> <version>${freemarker.version}</version> </dependency> <dependency> <groupid>javax.servlet</groupid> <artifactid>servlet-api</artifactid> <version>${servlet.version}</version> <scope>provided</scope> </dependency>
2. 在web.xml中加入spring的监听器和springmvc的servlet:
<listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class><!-- 监听容器事件,初始化和关闭web应用上下文并调用contextcleanuplistener清理资源 --> </listener> <listener> <listener-class>org.springframework.web.context.contextcleanuplistener</listener-class><!-- web应用关闭时,清理servletcontext中spring相关的可销毁资源 --> </listener> <servlet> <servlet-name>hbatis</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <!--<init-param> <param-name>contextconfiglocation</param-name> <param-value>/web-inf/hbatis-servlet.xml</param-value> </init-param>--><!-- 未配置时,springmvc会到web-inf目录下找${project.name}-servlet.xml --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>hbatis</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping>
3. 在web-inf下新建:
spring配置文件applicationcontext.xml:
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:context="http://www.springframework.org/schema/context" 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.xsd"> <context:property-placeholder location="classpath:/database.properties" /><!-- 数据库配置文件 --> <bean id="datasource" class="org.apache.commons.dbcp.basicdatasource" p:driverclassname="${driverclassname}" p:url="${url}" p:username="${user_name}" p:password="${password}" /><!-- 数据源配置 --> <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"><!-- sqlsessionfactory对象 --> <property name="datasource" ref="datasource" /><!-- 数据源 --> <property name="configlocation" value="classpath:configuration.xml" /><!-- mybatis配置文件 --> <!--<property name="mapperlocations" value="classpath*:com/john/hbatis/model/*.xml" />--><!-- 可以在configuration.xml或此处配置映射文件,但其中不能有相同id的parametermap, resultmap或sql等 --> </bean> <bean id="mapperconfigurer" class="org.mybatis.spring.mapper.mapperscannerconfigurer"><!-- 扫描指定包以获取映射器 --> <property name="basepackage" value="com.john.hbatis.mapper" /> </bean> </beans>
类路径下的database.properties:
driverclassname=com.mysql.jdbc.driver url=jdbc:mysql://localhost:3306/mybatis?characterencoding=utf8 user_name=root password=123456
注:因为mapperscannerconfigurer可能会导致username取的是系统用户的账号,而造成数据库连接失败,所以改成其它值:user_name。
springmvc配置文件hbatis-servlet.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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven /><!-- 注册requestmappinghandlermapping, requestmappinghandleradapter和exceptionhandlerexceptionresolver以提供对@requestmapping,@exceptionhandler等注解的支持 --> <context:component-scan base-package="com.john.hbatis.controller" /><!-- 扫描控制器包下有特定注解的类,并实例化和依赖注入 --> <!-- freemarker视图处理器 --> <bean id="viewresolverftl" class="org.springframework.web.servlet.view.freemarker.freemarkerviewresolver"> <property name="viewclass" value="org.springframework.web.servlet.view.freemarker.freemarkerview"/> <property name="contenttype" value="text/html;charset=utf-8"/> <property name="prefix" value="" /> <property name="cache" value="false"/> <property name="viewnames"> <array> <value>*.ftl</value> </array> </property> <!--<property name="suffix" value=".ftl"/>--> <property name="order" value="0"/><!-- 优先级,数值越小优先级越高 --> </bean> <bean id="freemarkerconfig" class="org.springframework.web.servlet.view.freemarker.freemarkerconfigurer"> <property name="templateloaderpaths"> <list> <value>/web-inf/ftl/</value><!-- 模板加载路径 --> </list> </property> </bean> </beans>
4. mvc:
控制层:usercontroller.java
@controller @requestmapping("/article") public class usercontroller { @autowired iusermapper mapper; @requestmapping("/list") public string showall(modelmap modelmap) { list<article> articles = mapper.getarticlesbyuserid(1); modelmap.addattribute("articles", articles); return "main.ftl"; } }
视图层:main.ftl:
<#list articles as article> <div>${article.id}. ${article.title}: ${article.content}</div> </#list>
5. 启动工程,浏览器输入:http://localhost:8080/hbatis/article/list.htm查看结果。
上一篇: JDK环境变量配置教程分享
下一篇: jQuery 动画效果代码分享