(可以跑通的,有数据库的,mchange+ aop )springmvc+jdbctemplate+mchange+multidatasource

简介:    基于 上篇文章  mybatis +springmvc+ mchange+multidatasource 没有跑通 , 一直没有找到 问题所在,现在 用 jdbctemplate 是可以跑通的 ,,,,           (可以跑通的,有数据库的,mchange+...

 

 基于 上篇文章  mybatis +springmvc+ mchange+multidatasource 没有跑通 , 一直没有找到 问题所在,现在 用 jdbctemplate 是可以跑通的 ,,,,

 

 

 

 

 

(可以跑通的,有数据库的,mchange+ aop )springmvc+jdbctemplate+mchange+multidatasource 

下载:  http://download.csdn.net/download/knight_black_bob/9245103

 

 



 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:aop="http://www.springframework.org/schema/aop"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd    
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd    
    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd    
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd    
    http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd    
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd    
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd    
    http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd    
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd    
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd    
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">

	<context:annotation-config />
	<aop:aspectj-autoproxy proxy-target-class="true" />
  
    <context:component-scan base-package="com.baoy"  >
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:db-config.properties" />
	</bean>


	<bean id="dataSourceOne" class="com.mchange.v2.c3p0.ComboPooledDataSource"   destroy-method="close">  
	   <property name="driverClass" value="${one.jdbc.driverClass}" />
		<property name="jdbcUrl" value="${one.jdbc.url}"/>
		<property name="user" value="${one.jdbc.user}"/>
		<property name="password" value="${one.jdbc.password}"/>
		<property name="initialPoolSize" value="${one.jdbc.initialPoolSize}"/>
		<property name="minPoolSize" value="${one.jdbc.minPoolSize}"/>
		<property name="maxPoolSize" value="${one.jdbc.maxPoolSize}"/>
		<property name="checkoutTimeout" value="${one.jdbc.checkoutTimeout}" />
		<property name="idleConnectionTestPeriod" value="${one.jdbc.idleConnectionTestPeriod}"/>
		<property name="maxIdleTime" value="${one.jdbc.maxIdleTime}"/>
		<property name="maxStatements" value="${one.jdbc.maxStatements}"/>
		<property name="testConnectionOnCheckout" value="${one.jdbc.testConnectionOnCheckout}"/>
	</bean>

	 

	<bean id="dataSourceTwo" class="com.mchange.v2.c3p0.ComboPooledDataSource"   destroy-method="close">  
	    <property name="driverClass" value="${two.jdbc.driverClass}" />
		<property name="jdbcUrl" value="${two.jdbc.url}"/>
		<property name="user" value="${two.jdbc.user}"/>
		<property name="password" value="${two.jdbc.password}" />
		<property name="initialPoolSize" value="${two.jdbc.initialPoolSize}"/>
		<property name="minPoolSize" value="${two.jdbc.minPoolSize}"/>
		<property name="maxPoolSize" value="${two.jdbc.maxPoolSize}"/>
		<property name="checkoutTimeout" value="${two.jdbc.checkoutTimeout}" />
		<property name="idleConnectionTestPeriod" value="${two.jdbc.idleConnectionTestPeriod}"/>
		<property name="maxIdleTime" value="${two.jdbc.maxIdleTime}"/>
		<property name="maxStatements" value="${two.jdbc.maxStatements}"/>
		<property name="testConnectionOnCheckout" value="${two.jdbc.testConnectionOnCheckout}"/>
	</bean>
    
     <bean id="dataSource" class="com.baoy.dynamic.DynamicDataSource">
		<property name="targetDataSources">
			<map key-type="java.lang.String">
				<entry key="dataSourceOne" value-ref="dataSourceOne" />
				<entry key="dataSourceTwo" value-ref="dataSourceTwo" />
			</map>
		</property>
		<property name="defaultTargetDataSource" ref="dataSourceOne" />
	  </bean>

	 <bean id="dataSourceInterceptor" class="com.baoy.dynamic.DataSourceInterceptor" />

	<aop:config>
		<aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor">
			<aop:pointcut id="dsone" expression="execution(* com.baoy.oneweb.dao.*.*(..))" />
			<aop:pointcut id="dstwo" expression="execution(* com.baoy.twoweb.dao.*.*(..))" />
			<aop:before method="setDataSourceOne" pointcut-ref="dsone"/>
			<aop:before method="setDataSourceTwo" pointcut-ref="dstwo"/>
		</aop:aspect>
	</aop:config>


    <bean id="jdbcTemplate"   class="org.springframework.jdbc.core.JdbcTemplate">  
        <property name="dataSource">  
            <ref bean="dataSource" />  
        </property>  
    </bean> 
</beans>   

 

 

springMvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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:oxm="http://www.springframework.org/schema/oxm"
	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/oxm http://www.springframework.org/schema/oxm/spring-oxm-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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
	<!-- 激活Spring注解方式:自动扫描,并注入bean -->
	<context:component-scan base-package="com.baoy.oneweb.action" /> 
	<context:component-scan base-package="com.baoy.twoweb.action" /> 

	
	<!-- 配置视图解析 -->
     <bean  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
        p:prefix="" p:suffix=".jsp">  
        <property name="order" value="0" />  
    </bean> 
	 <!-- 默认的注解映射的支持 -->
	<mvc:annotation-driven/>
	
	
	 
	
</beans>

 

 

 

web.xml

<?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:jsp="http://java.sun.com/xml/ns/javaee/jsp"
	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_3_0.xsd"
	version="3.0">
	<display-name></display-name>

	<!-- welcome page -->
	<welcome-file-list>
		<welcome-file>/back/jsp/main.jsp</welcome-file>
	</welcome-file-list>


	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext*.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>




	<!-- springmvc -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springMVC-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>



</web-app>

 

 

 

 

 

DatabaseContextHolder。java

 

 

package com.baoy.dynamic;

public class DatabaseContextHolder {

	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();  
	  
    public static void setCustomerType(String customerType) { 
        contextHolder.set(customerType);  
    }  
  
    public static String getCustomerType() {  
        return contextHolder.get();  
    }  
  
    public static void clearCustomerType() {  
        contextHolder.remove();  
    }  
	    
}

 

 

DataSourceInterceptor.java

 

package com.baoy.dynamic;
 
   
public class DataSourceInterceptor {   
    public void setDataSourceOne() {  
        DatabaseContextHolder.setCustomerType("dataSourceOne");  
    }  
       
    public void setDataSourceTwo() {  
        DatabaseContextHolder.setCustomerType("dataSourceTwo");  
    }   
}  

 

DynamicDataSource.java

package com.baoy.dynamic;
 
 

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
 

public class DynamicDataSource  extends AbstractRoutingDataSource{  
  
	  
    @Override  
    protected Object determineCurrentLookupKey() {   
        return DatabaseContextHolder.getCustomerType();   
    }
 
    
}  

 

 

UserDaoImpl.java

package com.baoy.oneweb.daoimpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; 
import org.springframework.stereotype.Repository;

import com.baoy.common.bean.User;
import com.baoy.oneweb.dao.UserDao; 

@Repository
public class UserDaoImpl   implements UserDao {
	

	 @Autowired 
	 private JdbcTemplate jdbcTemplate;
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	
	@SuppressWarnings("rawtypes")
	private class UserRowMapper implements RowMapper {

//		userId,userName,password,tel,sex,description
		@Override
		public User mapRow(ResultSet rs, int i) throws SQLException {
			User user = new User(); 
			user.setUserId(rs.getInt("userId"));
			user.setUserName(rs.getString("userName"));
			user.setPassword(rs.getString("password"));
			user.setTel(rs.getString("tel"));
			user.setSex(rs.getString("sex"));
			user.setDescription(rs.getString("description"));
			return user;
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> allUser() {
		String sql = "select * from t_user ";
		return   this.getJdbcTemplate().query(sql, new UserRowMapper());
	}

	@Override
	public void delUser(int userId) {
		String sql = "delete from t_user where userId ='"+userId+"'"; 
	    this.getJdbcTemplate().update(sql );
		
	}

	@Override
	public User user(int userId) {
		String sql = "select * from t_user where  userId ='"+userId+"'"; 
		List<User> userList = this.getJdbcTemplate().query(sql, new UserRowMapper());
		if (userList !=null && userList.size() > 0 ) {
			return userList.get(0);
		}else{
			return null;	
		}
	}

	@Override
	public void updateUser(User user) {
		String sql = "update t_user set userName=?,password=?,tel=?,sex=?,description=?";
		  this.getJdbcTemplate().update(sql, new Object[] {
					 user.getUserName(),
					 user.getPassword(),
					 user.getTel(),
					 user.getSex(),
					 user.getDescription()
			 });
	}

	@Override
	public void addUser(User user) {
		String sql = "insert into t_user(userName,password,tel,sex,description) values (?,?,?,?,?)";
		 this.getJdbcTemplate().update(sql, new Object[] {
				 user.getUserName(),
				 user.getPassword(),
				 user.getTel(),
				 user.getSex(),
				 user.getDescription()
		 });
	}


}

 service

package com.baoy.oneweb.service;

import java.util.List; 

import com.baoy.common.bean.User; 
 public interface UserService {
 
   public List<User> allUser();

   public void delUser(int userId);
   public User user(int userId);

   public void updateUser(User user);

   public void addUser(User user);

}

 

 

 

action

package com.baoy.oneweb.action;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.baoy.common.bean.User;
import com.baoy.oneweb.service.UserService;
 

@Controller
public class UserController {

       
      @Autowired
      UserService userService;

      @RequestMapping(value = "/userView.do")
      public String userView(ModelMap modelMap,String pageNo, String choice, HttpSession session){
            List<User> userList = userService.allUser();  
           modelMap.put("userList", userList);
           return "back/jsp/user/userView";
     }

      @RequestMapping(value = "/userDel{userId}.do")
      public String userDel(@PathVariable("userId")int userId ,ModelMap modelMap,String pageNo, String choice, HttpSession session){
             userService.delUser(userId);
             String message1="删除成功";
             String message2="请返回……";
             String  url="userView.do";
             modelMap.put("message1", message1);
             modelMap.put("message2", message2);
             modelMap.put("url", url);
            return "infomationShow";
      }

      @RequestMapping(value ="/userGoAdd.do")
             public String userGoAdd(ModelMap modelMap,String pageNo, String choice, HttpSession session){
             return "back/jsp/user/userAdd";
      }

      @RequestMapping(value = "/userAdd.do",method=RequestMethod.POST)
      public String userAdd(User form,ModelMap modelMap,String pageNo, String choice, HttpSession session){
             userService.addUser(form);
             String message1="添加成功";
             String message2="请返回……";
             String  url="userView.do";
             modelMap.put("message1", message1);
             modelMap.put("message2", message2);
            modelMap.put("url", url);
             return "infomationShow";
      }

      @RequestMapping(value = "/userGoUpdate{userId}.do")
      public String userGoUpdate(@PathVariable("userId")int userId ,ModelMap modelMap,String pageNo, String choice, HttpSession session){
            User user = userService.user(userId);
           modelMap.put("user", user);
           return "back/jsp/user/userUpdate";
      }

      @RequestMapping(value = "/userUpdate.do",method=RequestMethod.POST)
      public String userUpdate(User form,ModelMap modelMap,String pageNo, String choice, HttpSession session){
             userService.updateUser(form);
             String message1="修改成功";
             String message2="请返回……";
             String  url="userView.do";
             modelMap.put("message1", message1);
             modelMap.put("message2", message2);
             modelMap.put("url", url);
             return "infomationShow";
      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。



 
 
 谢谢您的赞助,我会做的更好!

 

 

目录
相关文章
|
1月前
|
Java 关系型数据库 MySQL
springboot学习四:springboot链接mysql数据库,使用JdbcTemplate 操作mysql
这篇文章是关于如何使用Spring Boot框架通过JdbcTemplate操作MySQL数据库的教程。
27 0
springboot学习四:springboot链接mysql数据库,使用JdbcTemplate 操作mysql
|
3月前
|
SQL 数据库
Spring5入门到实战------13、使用JdbcTemplate操作数据库(批量增删改)。具体代码+讲解 【下篇】
这篇文章是Spring5框架的实战教程,深入讲解了如何使用JdbcTemplate进行数据库的批量操作,包括批量添加、批量修改和批量删除的具体代码实现和测试过程,并通过完整的项目案例展示了如何在实际开发中应用这些技术。
Spring5入门到实战------13、使用JdbcTemplate操作数据库(批量增删改)。具体代码+讲解 【下篇】
|
3月前
|
XML 数据库 数据格式
Spring5入门到实战------14、完全注解开发形式 ----JdbcTemplate操作数据库(增删改查、批量增删改)。具体代码+讲解 【终结篇】
这篇文章是Spring5框架的实战教程的终结篇,介绍了如何使用注解而非XML配置文件来实现JdbcTemplate的数据库操作,包括增删改查和批量操作,通过创建配置类来注入数据库连接池和JdbcTemplate对象,并展示了完全注解开发形式的项目结构和代码实现。
Spring5入门到实战------14、完全注解开发形式 ----JdbcTemplate操作数据库(增删改查、批量增删改)。具体代码+讲解 【终结篇】
|
3月前
|
SQL XML Java
Spring5入门到实战------12、使用JdbcTemplate操作数据库(增删改查)。具体代码+讲解 【上篇】
这篇文章是Spring5框架的实战教程,详细讲解了如何使用JdbcTemplate进行数据库的增删改查操作,包括在项目中引入依赖、配置数据库连接池、创建实体类、定义DAO接口及其实现,并提供了具体的代码示例和测试结果,最后还提供了完整的XML配置文件和测试代码。
Spring5入门到实战------12、使用JdbcTemplate操作数据库(增删改查)。具体代码+讲解 【上篇】
|
5月前
|
SQL druid Java
传统后端SQL数据层替代解决方案: 内置数据源+JdbcTemplate+H2数据库 详解
传统后端SQL数据层替代解决方案: 内置数据源+JdbcTemplate+H2数据库 详解
61 1
|
6月前
|
前端开发 Java 关系型数据库
使用IDEA搭建一个Spring + AOP (权限管理 ) + Spring MVC
使用IDEA搭建一个Spring + AOP (权限管理 ) + Spring MVC
|
6月前
|
Java 关系型数据库 MySQL
Spring Boot使用JdbcTemplate操作mysql数据库实战(附源码 超详细)
Spring Boot使用JdbcTemplate操作mysql数据库实战(附源码 超详细)
179 0
|
XML 开发框架 Java
《Spring6核心源码解析》已完结,涵盖IOC容器、AOP切面、AOT预编译、SpringMVC,面试杠杠的!
全网首个全面解析Spring6核心源码的专栏,涵盖:IOC容器、AOP切面、声明式事务、AOT预编译和SpringMVC,让你从根本上彻底掌握Spring6核心技术。
524 1
《Spring6核心源码解析》已完结,涵盖IOC容器、AOP切面、AOT预编译、SpringMVC,面试杠杠的!
|
Oracle NoSQL 关系型数据库
SpringBoot-13-使用JdbcTemplate链接Mysql数据库
在企业项目开发者,数据库的使用是必不可少的一部分,常用的数据库有mysql、oracle、sqlserver、redis等,我们接下来的几章会介绍SpringBoot中如何使用数据库,本章就介绍使用JdbcTemplate链接mysql。
123 0
|
JSON 前端开发 数据库
JdbcTemplate实操查询数据库表中所有记录信息(十六课)
JdbcTemplate实操查询数据库表中所有记录信息(十六课)
82 0
下一篇
无影云桌面