与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://.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查看结果。