Integration with Spring3
As the basic framework, Spring can integrate back-end frameworks such as Hibernate, MyBatis, etc.
The previous article introduces the use of MyBatis alone, and the general logic is:
sqlSessionFactory <- configuration file (including database connection configuration)
IXxxMapper <- sqlSession <- sqlSessionFactory
<- mapper interface <- mapper xml
After obtaining IxxMapper, you can call its method for data interaction.
When integrating with Spring, the above objects need to be managed as beans:
dataSource bean <- Database connection configuration
sqlSessionFactory bean <- dataSource
<- configuration file
userMapper bean <- sqlSessionFactory
<- mapper interface
1. Add dependencies in 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><!-- Several objects of mybatis are wrapped into spring beans --> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <dependency><!-- spring context uses spring-jdbc to connect to the database --> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency><!-- dataSource is an instance of 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. Create beans-da.xml file under the classpath:
<?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"><!-- Database Connection 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"><!-- sqlSessionFactory bean --> <property name="dataSource" ref="dataSource" /><!-- Data Source--> <property name="configLocation" value="classpath:Configuration.xml" /><!-- Configuration file--> </bean> <bean id="userMapper"><!-- user map bean--> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> <property name="mapperInterface" value="com.john.hbatis.mapper.IUserMapper" /><!-- Mapping interface--> </beans>
3. Test class:
@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 = mappper.getUserById(1); log.info("Name: {}, address: {}", user.getName(), user.getAddress()); } } Integration with SpringMVC
Here we build on integration with Spring3:
1. Add SpringMVC and Freemarker dependencies to pom.xml:
<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. Add Spring's listener and SpringMVC's servlet in web.xml:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class><!-- Listen to container events, initialize and close the web application context and call ContextCleanupListener to clean up resources --> </listener> <listener> <listener-class>org.springframework.web.context.ContextCleanupListener</listener-class><!-- Clean up spring-related destructible resources in ServletContext when the web application is closed--> </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>--><!-- When not configured, SpringMVC will look for ${project.name}-servlet.xml in the WEB-INF directory --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>hbatis</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping>3. Create a new one under WEB-INF:
Spring configuration file 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" /><!-- Database Configuration File--> <bean id="dataSource" p:driverClassName="${driverClassName}" p:url="${url}" p:username="${user_name}" p:password="${password}" /><!-- Data source configuration --> <bean id="sqlSessionFactory"><!-- sqlSessionFactory object--> <property name="dataSource" ref="dataSource" /><!-- Data source--> <property name="configLocation" value="classpath:Configuration.xml" /><!-- myBatis configuration file--> <!--<property name="mapperLocations" value="classpath*:com/john/hbatis/model/*.xml" />--><!-- You can configure the mapping file in Configuration.xml or here, but you cannot have parameterMap, resultMap, sql, etc. with the same id --> </bean> <bean id="mapperConfigurer"><!-- Scan the specified package to get the mapper--> <property name="basePackage" value="com.john.hbatis.mapper" /> </bean> </beans>database.properties under the classpath:
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8 user_name=root password=123456
Note: Because MapperScannerConfigurer may cause the username to fetch the user's account, causing the database connection to fail, so it is changed to another value: user_name.
SpringMVC configuration file 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 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven /><!-- Register RequestMappingHandlerMapping, RequestMappingHandlerAdapter and ExceptionHandlerExceptionResolver to provide support for annotations such as @RequestMapping, @ExceptionHandler, etc. --> <context:component-scan base-package="com.john.hbatis.controller" /><!-- Scan the class with specific annotations under the controller package, instantiate and dependency injection --> <!-- FreeMarker view processor--> <bean id="viewResolverFtl"> <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"/><!-- Priority, the smaller the value, the higher the priority--> </bean> <bean id="freemarkerConfig"> <property name="templateLoaderPaths"> <list> <value>/WEB-INF/ftl/</value><!-- Template loading path--> </list> </property> </bean> </beans>
4. MVC:
Control layer: UserController.java
@Controller @RequestMapping("/article") public class UserController { @Autowired IUserMapper mapper; @RequestMapping("/list") public String showAll(ModelMap modelMap) { List<Article> articles = mappper.getArticlesByUserId(1); modelMap.addAttribute("articles", articles); return "main.ftl"; } }View layer: main.ftl:
<#list articles as article> <div>${article.id}. ${article.title}: ${article.content}</div> </#list>5. Start the project, and enter the browser: http://localhost:8080/hbatis/article/list.htm to view the results.