SpringMVC和Mybatis的整合的工作原理
SpringMVC和Mybatis的整合
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203
在做這個項目之前,我們的前提條件是:你已經(jīng)有一個能運行的SpringMVC的最簡單的項目了。請同學們參考我的SpringMVC那章。做這個項目關鍵在于導包,請參考下圖:
SpringMVC和Mybatis的整合的工作原理
馬克-to-win: org.mybatis.spring.mapper.MapperScannerConfigurer會自動往Spring容器注入 com.mapper目錄下所有的Mapper比如RegisterMapper(這就是為什么在Controller當中你能用@Resource注解找到RegisterMapper的實例的原因),條件是org.mybatis.spring.SqlSessionFactoryBean類的實例已經(jīng)在Spring容器中(實際上id是多少都無所謂,這里就是sqlSessionFactoryqqqq,因為反正也沒有人調用它,只要有實例在容器中就行),有了它,MapperScannerConfigurer才能正常工作,因為SqlSessionFactoryBean的一個屬性是 dataSource,它掌握著連接數(shù)據(jù)庫的密碼等。
例 1.4
<html>
<head>
<title>Spring 3.0</title>
</head>
<body>
<a href="helloa.do">Say Hello</a>
</body>
</html>
spring-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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="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">
<context:component-scan
base-package="com" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName"
value="com.mysql.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/test"></property>
<property name="username"
value="root"></property>
<property name="password"
value="1234"></property>
</bean>
<!-- 通過掃描的模式,掃描目錄在com.mapper目錄下,把所有mapper都注入到Spring當中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mapper" />
</bean>
<!-- 沒有以下的話,所有的mapper都不能創(chuàng)建,服務器啟動過程報錯-->
<bean id="sqlSessionFactoryqqqq" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
package com;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.mapper.RegisterMapper;
@Controller
public class HelloWorldController {
@Resource
private RegisterMapper registerMapper;
@RequestMapping("/helloa")
public void helloWorld(HttpServletResponse res) throws IOException {
Register register = registerMapper.selectByPrimaryKey(1);
System.out.println("register is "+register.toString());
res.sendRedirect("index.jsp");
}
}
運行index.jsp以后,console輸出結果是:
register is id:1
name:張三
age:13