Spring MVC的多数据库连接

首先,这个东西我找了好多文章,怕忘记,现在做出总结

  • 我们先搭建一个Spring MVC项目
  • 我用的是IDEA工具,搭建的时候使用的是Maven框架,就是我选中这个

下一步就好了,第一个是名字,第二个是存放的路径

  • 新建完,就开始搭建项目结构
  • Spring MVC由Model、View、Controller 组成所以项目结构为

  • 首先进来,是没有config这个文件夹的,这个用于存放,配置文件,数据库配置文件啊什么的,这个等会再说
  • 我简历了项目结构,分别为:Controller,dao、enity(这个名字不知道拼对没)、mapper、service、test、unit
  1. Controller:控制器包这个包用来控制访问的视图以及参数的处理
  2. dao:数据库操作包,这个包是放接口的,用于数据库的操作
  3. enity:实体类包,所谓一个表对应一个类,我觉得可以灵活使用不要拘泥。
  4. mapper:数据库映射文件,每个文件对应一个接口,数据库的操作语句就是在这写的。
  5. service:业务层,执行业务逻辑的地方。
  6. test:测试包,用于测试语句是否正常,有人用单元测试,我比较喜欢写测试包,舒服。
  7. unit:用于存放工具类的地方,工具!
  • 现在说一下config包,这个包用于存放资源文件,我起名是这个,你们喜欢就用cfig都行,随意。
  • 我一般放在项目的最外层,当然创建包它还要识别你的文件夹是不是资源文件夹,这个要你自己说。
  • 怎么说,有两种方法
  • 第一种右键文件夹的方式第三个就是了。

  • 第二种

  • 就是这样
  • 然后进来的时候src,还不是蓝色的,也要相同的操作
  • 关键点:webapp也要标记

  • 项目报错建议来找不同
  • 接下来说config里放了啥,多数据源开始了,注意看,这个是数据库配置信息文件,我配了两个数据源信息

  • 开始写文件了,首先配置数据库信息获取
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
	<util:properties id="db" location="classpath:jdbc.properties" />
	<bean id="dataSourceA" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="#{db.jdbcdriver}" />
		<property name="url" value="#{db.jdbcurl}" />
		<property name="username" value="#{db.jdbcusername}" />
		<property name="password" value="#{db.jdbcpassword}" />
	</bean>
	<bean id="dataSourceB" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="#{db.driver}" />
		<property name="url" value="#{db.url}" />
		<property name="username" value="#{db.username}" />
		<property name="password" value="#{db.password}" />
	</bean>
	<bean id="dataSource" class="main.unit.DynamicDataSource">
		<!-- 通过key-value的形式来关联数据源 -->
		<property name="targetDataSources">
			<map key-type="java.lang.String">
				<entry value-ref="dataSourceA" key="dataSourceA"></entry>
				<entry value-ref="dataSourceB" key="dataSourceB"></entry>
			</map>
		</property>
		<property name="defaultTargetDataSource" ref="dataSourceA" >
		</property>
	</bean>
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="mapperLocations" value="classpath:main/mapper/*.xml"></property>
	</bean>
	<!-- 将持久层包中所有接口扫描注册成MapperFactoryBean对象 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	    <property name="basePackage" value="main.dao"></property>
	</bean>
</beans>
  • 上面是数据源配置,properties文件的信息读取不会可以百度一下,我们配置好数据源就要用到工具类了,我在工具类包新建了一个工具类
  • 我给的默认数据库是A
package main.unit;

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

public class DynamicDataSource extends AbstractRoutingDataSource {
    public static final String SOURCE_A = "dataSourceA";
    public static final String SOURCE_B = "dataSourceB";
    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();
    }
    @Override
    protected Object determineCurrentLookupKey() {
        return getCustomerType();
    }
}
  • 这个类是继承于 AbstractRoutingDataSource类,感兴趣可以看看源码,不多。
  • 定义的两个变量就是数据库的名称(自己取的,喜欢可以叫fwkt,张三都可以),不过后面的值可不能乱写
  • 然后我们看到几个方法,最主要的是最后一个,不能少,determineCurrentLookupKey()这个方法是指定使用哪个数据库的
  • 接着我们先测试一下,为了节省时间,我把用到的类都丢出来
package main.dao;
import main.enity.Recommendation;
import java.util.List;


public interface Testdao {
    public List<Recommendation> find();

}
  •  实体类,其实查出来没有这么多
package main.enity;

public class Recommendation {
    private int userid;
    private String username;
    private int eferencesid;
    private String power;
    private int buynum;
    private double monery;

    public Recommendation(int userid, String username, int eferencesid, String power, int buynum, double monery) {
        this.userid = userid;
        this.username = username;
        this.eferencesid = eferencesid;
        this.power = power;
        this.buynum = buynum;
        this.monery = monery;
    }

    public Recommendation() {
        super();
    }

    public int getBuynum() {
        return buynum;
    }

    public void setBuynum(int buynum) {
        this.buynum = buynum;
    }

    public String getPower() {
        return power;
    }

    public void setPower(String power) {
        this.power = power;
    }

    public double getMonery() {
        return monery;
    }

    public void setMonery(double monery) {
        this.monery = monery;
    }

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getEferencesid() {
        return eferencesid;
    }

    public void setEferencesid(int eferencesid) {
        this.eferencesid = eferencesid;
    }

    @Override
    public String toString() {
        return "Recommendation{" +
                "userid=" + userid +
                ", username='" + username + '\'' +
                ", eferencesid=" + eferencesid +
                ", power='" + power + '\'' +
                ", buynum=" + buynum +
                ", monery=" + monery +
                '}';
    }
}
  • mapper文件,namespace="main.dao.Testdao",这个指定包名,表示使用哪个接口的方法,id是方法名,resultType是返回值类型(全称)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
        "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="main.dao.Testdao">
   <select id="find" resultType="main.enity.Recommendation">
      select * from vbl_recommendation
   </select>
</mapper>
  • 这个是service的接口
package main.service.ImpI;

import main.enity.Recommendation;
import java.util.List;

public interface TestImpi {
    public List<Recommendation> find();
}
  • service继承于他,使用,数据库接口,如下:
package main.service;

import main.dao.Testdao;
import main.enity.Recommendation;
import main.service.ImpI.TestImpi;
import main.unit.DynamicDataSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
public class testservice implements TestImpi {
    @Autowired
    private Testdao testdao;
    @Override
    public List<Recommendation> find() {
        return testdao.find();
    }
}
  • 测试类环节
import main.dao.Testdao;
import main.enity.Recommendation;
import main.unit.DynamicDataSource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Test1 {

	public static void main(String[] args) {
		AbstractApplicationContext ac = new ClassPathXmlApplicationContext("application-dao.xml");
		SqlSessionFactory factory = ac.getBean("sqlSessionFactory", SqlSessionFactory.class);
        //切换数据源的操作在这
		DynamicDataSource.setCustomerType(DynamicDataSource.SOURCE_A);//直接使用
		SqlSession ss = factory.openSession(true);
		Testdao testdao = ss.getMapper(Testdao.class);
		List<Recommendation> recommendations = testdao.find();
		System.out.println(recommendations);
		System.out.println("结束");
		ac.close();
	}

}
  • 运行结果,A数据库

  •  B数据库,成功!

  • 还有一些文件,自己测后面的吧
  • Controller文件
import main.dao.Testdao;
import main.enity.Recommendation;
import main.unit.DynamicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class TestConller {
    @Autowired
    Testdao testdao;
    @Autowired
    DynamicDataSource dynamicDataSource;
    @RequestMapping("ddd")
    public String test(){
        dynamicDataSource.setCustomerType(dynamicDataSource.SOURCE_A);
        List<Recommendation> recommendations = testdao.find();
        String string = recommendations.toString();
        System.out.println("==============================");
        System.out.println(string);
        return "index";
    }
}
  • service配置文件
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
	<context:component-scan base-package="main.service"></context:component-scan>
	
</beans>
  • springMVC配置文件
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
	<!-- 扫描包 -->
	<context:component-scan base-package="main.controller"></context:component-scan>
	<!-- 配置视图解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- /WEB-INF/index.jsp -->
		<property name="prefix" value="/WEB-INF/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!-- 处理静态资源 -->
	<mvc:annotation-driven />
	<mvc:default-servlet-handler />
</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"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
    <display-name>Test Maven Webapp</display-name>
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <!-- 编码过滤器 -->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application-*.xml</param-value>
    </context-param>
</web-app>
  • 最后,提醒一下各位,不要忘记导包

 

  • 我只是用到了几个包,看自己需要导,有人说,我没有怎么办,不急,用这个

  • 示范
<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.3</version>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.1</version>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>
    </dependency>
    <dependency>
      <groupId>net.sf.ezmorph</groupId>
      <artifactId>ezmorph</artifactId>
      <version>1.0.6</version>
    </dependency>
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.2.3</version>
      <classifier>jdk15</classifier>
    </dependency>
  </dependencies>

我的第一篇文章就这么结束了,希望我以后还记得

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC 是一种基于Spring框架的Web开发框架,它是基于模型-视图-控制器(MVC)设计模式来组织和管理Web应用程序的开发的。数据库事务是保证数据操作的一致性和可靠性的重要机制。 在Spring MVC中,数据库事务的实现主要依赖于Spring框架内置的事务管理器。Spring框架为我们提供了多种事务管理器的实现方式,例如基于JDBC的DataSourceTransactionManager和基于JPA的JpaTransactionManager等。这些事务管理器实现了Spring的PlatformTransactionManager接口,它负责管理和控制事务的生命周期。 Spring MVC中使用注解@Transactional来标注需要参与事务管理的方法或类。被@Transactional标注的方法或类,会在运行时被Spring框架内置的AOP机制拦截,以实现事务的控制。当方法被调用时,Spring框架首先会检查当前线程是否已经有一个事务实例存在,如果不存在则创建一个新的事务,如果存在则加入已存在的事务中。 一旦事务创建成功,Spring框架会开始执行方法体中的业务逻辑操作。如果方法执行成功,事务将会继续提交,操作的结果将会永久保存到数据库中。如果方法执行失败或发生异常,Spring框架会回滚事务,将操作的结果恢复到之前的状态。这样可以确保在出现异常情况时,数据库的数据不会被污染或损坏。 事务的提交和回滚是由Spring框架的事务管理器来完成的。事务管理器负责管理事务的开始、提交和回滚等操作,并与底层的数据库连接进行交互。Spring框架还提供了各种配置选项,可以通过配置文件或注解来灵活地控制事务的传播行为、隔离级别、超时设置等。这些配置选项可以根据实际业务需求进行调整,以提供更好的性能和可靠性。 总而言之,Spring MVC中的数据库事务的实现原理是依赖于Spring框架提供的事务管理器和AOP机制。通过使用@Transactional注解,我们可以简单地将需要参与事务管理的方法或类进行标注,使其具备事务性的功能。这样可以实现对数据库操作的一致性和可靠性保证。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值