Java环境中MyBatis与Spring或Spring MVC框架的集成方法
与Spring3集成
Spring作为基础框架,可以集成后端框架,如Hibernate,MyBatis等。
前面是介绍单独使用MyBatis的,大致逻辑是:
sqlSessionFactory<-configurationfile(包括数据库连接配置)
IXxxMapper<-sqlSession<-sqlSessionFactory
<-mapperinterface<-mapperxml
得到IxxMapper后,就可以调用其方法进行数据交互了。
和Spring集成时,上面的这些对象需要作为bean来管理:
dataSourcebean<-数据库连接配置
sqlSessionFactorybean<-dataSource
<-configurationfile
userMapperbean<-sqlSessionFactory
<-mapperinterface
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文件:
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"> <beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"><!--数据库连接bean--> <propertyname="driverClassName"value="com.mysql.jdbc.Driver"/> <propertyname="url"value="jdbc:mysql://localhost:3306/hbatis?characterEncoding=utf8"/> <propertyname="username"value="root"/> <propertyname="password"value="123456"/> </bean> <beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><!--sqlSessionFactorybean--> <propertyname="dataSource"ref="dataSource"/><!--数据源--> <propertyname="configLocation"value="classpath:Configuration.xml"/><!--配置文件--> </bean> <beanid="userMapper"class="org.mybatis.spring.mapper.MapperFactoryBean"><!--user映射bean--> <propertyname="sqlSessionFactory"ref="sqlSessionFactory"/> <propertyname="mapperInterface"value="com.john.hbatis.mapper.IUserMapper"/><!--映射接口--> </bean> </beans>
3.测试类:
@ContextConfiguration(locations={"classpath:beans-da.xml"}) publicclassSpringIntegrationTestextendsAbstractTestNGSpringContextTests{ privatestaticfinalLoggerlog=LoggerFactory.getLogger(SpringIntegrationTest.class); @Resource IUserMappermapper; @Test publicvoidqueryTest(){ Useruser=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:
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholderlocation="classpath:/database.properties"/><!--数据库配置文件--> <beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="${driverClassName}" p:url="${url}" p:username="${user_name}" p:password="${password}"/><!--数据源配置--> <beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><!--sqlSessionFactory对象--> <propertyname="dataSource"ref="dataSource"/><!--数据源--> <propertyname="configLocation"value="classpath:Configuration.xml"/><!--myBatis配置文件--> <!--<propertyname="mapperLocations"value="classpath*:com/john/hbatis/model/*.xml"/>--><!--可以在Configuration.xml或此处配置映射文件,但其中不能有相同id的parameterMap,resultMap或sql等--> </bean> <beanid="mapperConfigurer"class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--扫描指定包以获取映射器--> <propertyname="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:
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven/><!--注册RequestMappingHandlerMapping,RequestMappingHandlerAdapter和ExceptionHandlerExceptionResolver以提供对@RequestMapping,@ExceptionHandler等注解的支持--> <context:component-scanbase-package="com.john.hbatis.controller"/><!--扫描控制器包下有特定注解的类,并实例化和依赖注入--> <!--FreeMarker视图处理器--> <beanid="viewResolverFtl"class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <propertyname="viewClass"value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/> <propertyname="contentType"value="text/html;charset=utf-8"/> <propertyname="prefix"value=""/> <propertyname="cache"value="false"/> <propertyname="viewNames"> <array> <value>*.ftl</value> </array> </property> <!--<propertyname="suffix"value=".ftl"/>--> <propertyname="order"value="0"/><!--优先级,数值越小优先级越高--> </bean> <beanid="freemarkerConfig"class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <propertyname="templateLoaderPaths"> <list> <value>/WEB-INF/ftl/</value><!--模板加载路径--> </list> </property> </bean> </beans>
4.MVC:
控制层:UserController.java
@Controller @RequestMapping("/article") publicclassUserController{ @Autowired IUserMappermapper; @RequestMapping("/list") publicStringshowAll(ModelMapmodelMap){ List<Article>articles=mapper.getArticlesByUserId(1); modelMap.addAttribute("articles",articles); return"main.ftl"; } }
视图层:main.ftl:
<#listarticlesasarticle> <div>${article.id}.${article.title}:${article.content}</div> </#list>
5.启动工程,浏览器输入:http://localhost:8080/hbatis/article/list.htm查看结果。