SpringMVC+Mybatis整合搭建

1.使用eclipse构建SpringMVC工程

    1.构建过程可参考eclipse构建springmvc

2.开始配置工程项目

    2.1.构建好的工程结构如下:

   2.2.使用maven管理项目,添加项目所依赖的jar包

2.3.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns="http://java.sun.com/xml/ns/javaee"   
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
                             http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   
         version="2.5" >  

  <display-name>bobo.smvc.example</display-name>
   <!-- 区分项目名称,防止默认重名 -->  
   <context-param>
     <param-name>webAppRootKey</param-name>
     <param-value>bobo.smvc.example</param-value>
   </context-param>
   
	<!-- Spring监听器  -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
   
   <!-- Spring的log4j监听器 -->  
   <listener>
     <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
   </listener>
   
   <!-- 字符集 过滤器  -->  
   <filter>
     <filter-name>CharacterEncodingFilter</filter-name>
     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
     
     <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
     </init-param>
     <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
     </init-param>
   </filter>
   <filter-mapping>
      <filter-name>CharacterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
   
   <!-- Spring上下文配置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:/spring/applicationContext.xml</param-value>
	</context-param>
   
    <!-- Spring view分发器 -->  
    <servlet>
       <servlet-name>dispatcher</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:/spring/dispatcher-servlet.xml</param-value>
       </init-param>
       <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
  <!-- 配置session存在时间 -->
  <session-config>
    <session-timeout>60</session-timeout>
  </session-config>
  
   <!-- Log4J 配置  -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
	    <param-value>classpath:log4j.properties</param-value>
	</context-param>	
    
   <!-- 默认起始页面 -->
   <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   
   <!-- 异常跳转页面 -->
   <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/WEB-INF/views/exception.jsp</location>
   </error-page>
</web-app>

  2.4.配置applicationContext.xml (这里只导入了另一个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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" 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.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd   
        http://www.springframework.org/schema/tx  
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">
	 
    <!-- 导入分割的spring配置文件 -->
	<import resource="applicationContext-datasource.xml"/>
</beans>

  2.5.配置dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"   
           xmlns:aop="http://www.springframework.org/schema/aop"   
           xmlns:context="http://www.springframework.org/schema/context"  
           xmlns:mvc="http://www.springframework.org/schema/mvc"   
           xmlns:tx="http://www.springframework.org/schema/tx"   
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
           xsi:schemaLocation="http://www.springframework.org/schema/aop   
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
            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   
            http://www.springframework.org/schema/tx   
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  
      
        <!-- 启用spring mvc 注解-->
        <mvc:annotation-driven />  
        
        <!-- 自动扫描的包名 ,使Spring支持自动检测组件,如注解的Controller-->  
        <context:component-scan base-package="com.bobo.controller" />
        <!-- 自动扫描的包名 ,使Spring支持自动检测组件,如注解的Service (在service的实现类上加@service时用)--> 
        <context:component-scan base-package="com.bobo.service" />  
      
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
            <property name="prefix" value="/WEB-INF/views/" />  
            <property name="suffix" value=".jsp" />  
        </bean>  
      
</beans>

  2.6.配置applicationContext-datasource.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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" 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.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd   
        http://www.springframework.org/schema/tx  
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">

<!-- 	<import resource="classpath:spring/datasource/detail3ydb.xml" /> -->
	 
	
	
	<tx:annotation-driven transaction-manager="txManager" />
    <!-- spring管理事务 -->
	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- 配置sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
		<property name="dataSource" ref="dataSource" />
		<property name="mapperLocations">
			<list>
				<value>classpath:mybatis/mapper/*Mapper.xml</value>
			</list>
		</property>
	</bean>
	<!-- 设置与事务有关的各种属性  -->
<!--  	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="insert*"  propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="del*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="save*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="remove*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="select*"  propagation="SUPPORTS"/>
			<tx:method name="get*"  propagation="SUPPORTS"/>
			<tx:method name="find*"  propagation="SUPPORTS"/>
			<tx:method name="query*"  propagation="SUPPORTS"/>
			<tx:method name="*" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice> --> 

	<!-- 声明切入点 -->
	<!-- <aop:config >
		<aop:pointcut id="loginPointCuts"
			expression="execution(* com.hc360.detail.sitemap.service..*.*(..))" />
			
		<aop:advisor advice-ref="txAdvice" pointcut-ref="loginPointCuts" />
	</aop:config> -->
	
	
	
	<!-- 通过扫描的模式,自动注入bean -->
    <bean name="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.bobo.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>


    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <!-- standard config -->
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
 
<!-- 		  <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/> -->
			<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
				<property name="driverClassName" value="${jdbc.driverClassName}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
				<property name="maxActive" value="${jdbc.maxActive}" />
				<property name="maxIdle" value="${jdbc.maxIdle}" />
				<property name="maxWait" value="${jdbc.maxWait}" />
			</bean> 
	
</beans>

  2.7.配置controller

package com.bobo.controller;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bobo.service.OnCorTableService;

@Controller
//@RequestMapping("/thello")
public class Hello {
	Logger loger= LoggerFactory.getLogger(Hello.class);
	
	@Autowired(required=true)
	OnCorTableService oncortableservice;
	
	@RequestMapping(value="/he/thell0.do")
	public String tHello(HttpServletRequest request,HttpServletResponse response,Model model){
		model.addAttribute("hello", "Hello,mvc");
		//System.out.println("hello.jsp");
		Long ucount= oncortableservice.getuserCount();//查询用户数量
		model.addAttribute("ucount", ucount+"");
		loger.info("用户人数:"+ucount);
		System.out.println("用户人数:"+ucount);
		return "hello";
	}
}

   2.8.配置service(OnCorTableService和实现类OnCorTableServiceImpl)

package com.bobo.service;

public interface OnCorTableService {

	public long getuserCount();
}

package com.bobo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bobo.dao.OnCorTableMapper;
import com.bobo.service.OnCorTableService;
@Service
public class OnCorTableImpl implements OnCorTableService{

	@Autowired(required=true)
	OnCorTableMapper oncortablemapper;
	
	@Override
	public long getuserCount() {
		// TODO Auto-generated method stub
		return oncortablemapper.getUsernameCount();
	}

}

   2.9.配置dao(OnCorTableMapper.java和OnCorTableMapper.xml)

package com.bobo.dao;

public interface OnCorTableMapper{
	/**
	 * 查询用户名个数
	* @author hc360
	* @version 1.0
	* @date 2014-11-10
	* @param 
	* @return Long
	 */
	Long getUsernameCount();
	
	/**
	 * 查询  增量 用户名个数
	* @author hc360
	* @version 1.0
	* @date 2014-11-10
	* @param 
	* @return Long
	 */
	Long getIncreaceUsernameCount(long turnStartId);

	
	Long getLastProviderIdByUsername(String username);
	
}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bobo.dao.OnCorTableMapper">
<select id="getUsernameCount" resultType="java.lang.Long">SELECT count(t.USERNAME) FROM on_cor_table t</select>
<select id="getIncreaceUsernameCount" resultType="java.lang.Long">SELECT count(t.USERNAME) FROM on_cor_table t where t.providerid >#{turnstartId}</select>
<select id="getLastProviderIdByUsername" resultType="java.lang.Long" parameterType="String">
SELECT t.providerid FROM on_cor_table t where t.USERNAME=#{username} </select>
</mapper>


2.10.配置jdbc.properties

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver

jdbc.url=jdbc:oracle:thin:@100.000.00.000:1521:bjdt4
jdbc.username=newhc
jdbc.password=bfdds06fd

jdbc.maxActive=20
jdbc.maxIdle=50
jdbc.maxWait=10000

jdbc0.url=jdbc:oracle:thin:@100.000.00.000:1521:bjdt4
jdbc0.username=newhc
jdbc0.password=bfdds06fd

2.11.配置log4j.properties

log4j.rootLogger=debug,console,filelog
### 输出信息到控制台###
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%d] [%t] (%F:%L) %-5p %c - %m%n
log4j.appender.console.Encoding=GB18030

### 输出DEBUG 级别以上的日志到=/smvc/logs/all/smvc.log ###
log4j.appender.filelog = org.apache.log4j.DailyRollingFileAppender
log4j.appender.filelog.File = /smvc/logs/all/smvc.log
log4j.appender.filelog.Encoding=GB18030
log4j.appender.filelog.layout = org.apache.log4j.PatternLayout
log4j.appender.filelog.DatePattern = '.'yyyy-MM-dd-HH
log4j.appender.filelog.layout.ConversionPattern =[%d] [%t] (%F:%L) %-5p %c - %m%n
log4j.appender.filelog.Threshold=DEBUG


到此为止一个简单的SpringMVC+Mybatis整合就完成了。。。。后续就是加入你自己的业务逻辑代码了~

项目git地址:https://git.oschina.net/Bobo0915/smvc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值