Spring3 整合 Mybatis3

Spring3 整合 Mybatis3

这两天,项目需要使用spring+ibatis,于是去网上下载了,结果发现和之前我用的版本变化不小,整了两天才将功能实现,不敢怠慢,赶紧写份博客记录一下。

首先是依赖的库:

接着是web.xml的配置,这里,我使用的是Spring3 MVC

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Log</display-name>
  
  <welcome-file-list>
  	<welcome-file>welcome.html</welcome-file>
  </welcome-file-list>
  
 	<!--日志配置文件的载入 --> 
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/classes/log4j.properties</param-value>
	</context-param>
	<!--Spring配置文件的载入 --> 
	<context-param>    
		<param-name>contextConfigLocation</param-name>    
		<param-value>classpath:applicationContext*.xml</param-value>    
	</context-param> 

	<!--Spring的ApplicationContext 载入 --> 
	<listener> 
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
	</listener>
	
	<!-- Spring字符集过滤 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf8</param-value>
		</init-param>
	</filter>
 
	<filter-mapping>
		<filter-name>encodingFilter</filter-name >
		<url-pattern>*.do</url-pattern>
	</filter-mapping>

<!-- Server启动时加载的应用 -->

<!-- Spring过滤器 -->
<servlet>
	<servlet-name>dispatchServlet</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:servlet-config.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>dispatchServlet</servlet-name>
	<url-pattern>*.do</url-pattern>
</servlet-mapping>
  
</web-app>

然后是spring的servlet配置servlet-config.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"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  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
   http://www.springframework.org/schema/mvc  
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
   
   <!-- 自动扫描bean,把作了注解的类转换为bean -->  
    <context:component-scan base-package="com.log.bean.dao, com.log.report.controller" />  
    
    <!-- 默认的注解映射的支持 -->  
    <mvc:annotation-driven/>
    <!-- 支持JSON数据格式 -->
    <bean  class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />  
    <bean  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >  
    	<property name="messageConverters">
  			<list>
   				<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
   					<property name="supportedMediaTypes">  
        				<list>  
            				<value>text/html;charset=UTF-8</value>  
        				</list>  
    				</property> 
   				</bean>
  			</list>
 		</property>
    </bean>
    
	<!-- 声明viewResolver -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/" />
		<property name="suffix" value=".html" />
	</bean>
	
	
</beans>

然后是Spring的Bean的配置文件applicationContext.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:aop="http://www.springframework.org/schema/aop"
             xmlns:tx="http://www.springframework.org/schema/tx"
             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
                     http://www.springframework.org/schema/aop
                     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                     http://www.springframework.org/schema/tx
                     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
           
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">    
		<property name="maxActive" value="20" />    
        <property name="maxIdle" value="20" />    
        <property name="maxWait" value="3000" />    
        <property name="testWhileIdle" value="true" />    
        <property name="timeBetweenEvictionRunsMillis" value="3600000" />    
        <property name="validationQuery" value="select 1" />    
        <property name="removeAbandoned" value="true" />    
        <property name="removeAbandonedTimeout" value="1" />    
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />    
		<property name="url" value="jdbc:mysql://localhost:53306/search" />    
		<property name="username" value="root" />    
		<property name="password" value="8bewp2rJHfRGrl9VTQmc" />    
	</bean>
	
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
    	<property name="configLocation" value="classpath:ibatis-config.xml" /> 
    	<property name="dataSource" ref="dataSource" /> 
    	<!-- mapper和resultmap配置路径 -->
    	<property name="mapperLocations">
			<list>
				<value>classpath:com/log/bean/mapper/*.xml</value>
    		</list>
    	</property>
	</bean>
	
	<!-- 通过扫描的模式,扫描目录在com/log/bean/mapper目录下,所有的mapper都继承
			SQLMapper接口的接口, 这样一个bean就可以了 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.log.bean.mapper"/>
		<property name="markerInterface" value="com.log.bean.mapper.SQLMapper"/>
	</bean>
	
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
 		<constructor-arg index="0" ref="sqlSessionFactory" />    
	</bean> 
	
  <!--事务配置-->
	<tx:annotation-driven transaction-manager="transactionManager" /> 
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" autowire="byName" />
	
</beans>

然后是MyBatis的配置ibatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- 别名 -->
	<typeAliases>
		<typeAlias type="com.log.bean.KeywordExportPVDataBean" alias="keyword_export_pv"/>
	</typeAliases>

</configuration>

接着是映射文件:

<mapper namespace="com.log.bean.mapper.KeywordExportPVMapper">
   
    <select id="getKeywordExportPVList" resultType="keyword_export_pv" parameterType="keyword_export_pv" statementType="STATEMENT">
    	<![CDATA[
    		select query, click_count, site, site_click_count, subsite, subsite_click_count, site_click_rate, subsite_click_rate 
    			from ${table} ${condition}
    	]]>
    </select>
    
    <select id="getKeywordExportPVTotalNumByDate" resultType="java.lang.String" parameterType="keyword_export_pv" statementType="STATEMENT">
    	<![CDATA[
    		select count(*)
    			from ${table} ${sumCondition}
    	]]>
    </select>
</mapper>


这样,配置就完成了:

接着我们要实现多个java类。

首先是Map类:

public interface SQLMapper {

}

public interface KeywordExportPVMapper extends SQLMapper{
	List<KeywordExportPVDataBean> getKeywordExportPVList(KeywordExportPVDataBean keywordExportPVDataBean);
	
	String getKeywordExportPVTotalNumByDate(KeywordExportPVDataBean keywordExportPVDataBean);
}

接着是DAO类:

import java.util.List;

import javax.inject.Inject;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Service;

import com.log.bean.KeywordExportPVDataBean;
import com.log.bean.mapper.KeywordExportPVMapper;

@Service
public class KeywordExportPVDaoImpl extends SqlSessionDaoSupport  implements KeywordExportPVDao{

	@Inject
	private KeywordExportPVMapper mapper;
	
	public List<KeywordExportPVDataBean> getKeywordExportPVList(
			KeywordExportPVDataBean keywordExportPVDataBean) {
		List<KeywordExportPVDataBean> result = mapper.getKeywordExportPVList(keywordExportPVDataBean);
		int index = (keywordExportPVDataBean.getPage() - 1) * keywordExportPVDataBean.getRows() + 1;
		for(KeywordExportPVDataBean data : result) {
			data.setId(index++);
		}
		return result;
	}
	
	public String getKeywordExportPVTotalNumByDate(KeywordExportPVDataBean keywordExportPVDataBean) {
		return mapper.getKeywordExportPVTotalNumByDate(keywordExportPVDataBean);
	}
	
}

一个java bean类

public class KeywordExportPVDataBean implements Serializable {
	
	private static final long serialVersionUID = 7729632882629489521L;
	。。。
}

最后,我们在Controller中调用它

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.log.bean.KeywordExportPVDataBean;
import com.log.bean.dao.KeywordExportPVDao;

@Controller
public class KeywordInfoController {
	
	@Inject
	KeywordExportPVDao keywordExportPVDao;
	
	@RequestMapping(value="getKeywordExportPVData.do", method=RequestMethod.POST)
	@ResponseBody
	public Object getKeywordExportPVInfo(KeywordExportPVDataBean req_data ){
		List<KeywordExportPVDataBean> rows = keywordExportPVDao.getKeywordExportPVList(req_data);
		String records = keywordExportPVDao.getKeywordExportPVTotalNumByDate(req_data);
		Map<String,Object> result = new HashMap<String,Object> ();
		result.put("records", Integer.valueOf(records));
		result.put("total", Integer.valueOf(records)/req_data.getRows() + 1);
		result.put("rows", rows);
		return result;
	}
	
}






评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值