ssm框架配置多数据源的方式

ssm框架配置多数据源的方式

	项目开发过程中,我们可能涉及到链接多个数据库进行数据存取等操作。这个时候我们就需要配置多个数据源。其中配置多数据源有很多种方式。
	话不多说,上教程。

1、首先搭建SSM框架,这就不必再多介绍。想必大家的项目里单数据源的情况下都已经能连上数据库了。

2、配置多数据源之前,我们肯定要知道我们这个数据源要连接的是什么库,比如Oracle,mysql,SQL Server等。配置前,我们需要把链接数据库的驱动jar包放到项目的lib下,因为有了驱动,我们才可以链接。(我以Oracle为例)

3、驱动弄好后,就是写配置文件了。配置文件里(一般放在properties文件中)写明address、url、账号、密码和其他连接配置等信息。

jdbcAddress=http\://10.10.20.58\:7001/hqoa/dist/index.html
jdbcUrl=jdbc\:oracle\:thin\:@192.168.1.124\:1521\:aaaa
jdbcDBUser=scott
jdbcDBPassword=1
oracle.maxconn=500 

4、新建一个PropertyUtil类,用于读取properties文件中的信息。

public class PropertyUtil {

    private static Properties prop = null;
    
    private static void init(){
    	if(prop == null){
			prop = new Properties();
			/*
			*在此写入要加载的文件名。
			*/
			loadProperties("/jdbc.properties");
		}
    }
    /**
     * 根据路径名称(相对classes路径)获取properties属性文件
     * @param propertiesPath
     * @return
     */
    private static void loadProperties(String propertiesPath) {
        InputStream inputStream = null;
        try {
            if (propertiesPath == null || "".equals(propertiesPath.trim())) {
                throw new IllegalArgumentException();
            }
            String suffix = ".properties";
            if (propertiesPath.toLowerCase().lastIndexOf(suffix) == -1) {
                propertiesPath += suffix;
            }
            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesPath);
            if (inputStream != null) {
                prop.load(inputStream);
            }
        } catch (Exception e) {
            Log4jUtil.error("Load Properties File Occured Error!", e);
            throw new RuntimeException(e);
        } finally {
            try{
                if(inputStream != null){
                    inputStream.close();
                }
            }catch(IOException e){
                Log4jUtil.error("Close InputStream Occured Error!", e);
            }
        }
    }
	/**
	 * 根据key获取properties属性文件对应的值
	 * @param key
	 * @return
	 */
	public static String getValue(String key) {
		init();
		return prop.getProperty(key);
	}
	/**
	 * 根据key获取properties属性文件对应的值
	 * @param key
	 * @param defaultValue 默认值(如果不存在或为空,则采用默认值)
	 * @return
	 */
	public static String getValue(String key, String defaultValue) {
		init();
		return prop.getProperty(key, defaultValue);
	}
	
}

5、这是最关键的一步了,怎么读取这些配置并实现数据库链接呢。我们可以新建一个BaseDao类。通过PropertyUtil获取各个属性,用Connection对象代表与数据库的链接。连接过程包括所执行的SQL语句和在该连接上所返回的结果。一个应用程序可与单个数据库有一个或多个连接,或者可与很多数据库有连接。打开连接与数据库建立连接的标准方法是调用DriverManager.getConnection()方法。

public class BaseDao {
    private static String url = PropertyUtil.getValue("jdbcUrl");
    private static String user = PropertyUtil.getValue("jdbcDBUser");
    private static String password = PropertyUtil.getValue("jdbcDBPassword");
    public Connection conn;
    public static Statement ps;
    public static ResultSet rs;
    // 连接数据库的方法 
    public Connection getConnection() {
       try {
           // 初始化驱动包
           Class.forName("oracle.jdbc.OracleDriver");
           // 根据数据库连接字符,名称,密码给conn
           conn = DriverManager.getConnection(url, user, password);
       } catch (Exception e) {
           e.printStackTrace();
       }
      return conn;
    }
    //关闭连接的方法
    public static void getColse(ResultSet rs,PreparedStatement psta,Connection conn){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(psta!=null){
			try {
				psta.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

6、在要执行的类里调用BaseDao,就可以实现多数据源的连接啦!!!!

	//此处是自己的功能逻辑代码
	public List<AttendanceRecodeDto> findAttendance(int empId) {
	Connection conn = null;
	PreparedStatement psta= null;
	ResultSet rs = null;
		try {
			BaseDao basedao=new BaseDao();
			conn = basedao.getConnection();
			conn.setAutoCommit(false);
			String sql = "select * from hpc_attendance_record  where emp_id=?";
			psta = conn.prepareStatement(sql);
			psta.setInt(1, empId);
			rs = psta.executeQuery();
			List<AttendanceRecodeDto> attendanceRecodeList=new ArrayList<AttendanceRecodeDto>();
			while(rs.next()){
				AttendanceRecodeDto ar=new AttendanceRecodeDto();
				ar.setHac_id(rs.getInt("hac_id"));
				ar.setEmp_id(rs.getInt("emp_id"));
				ar.setHac_gooffwork_time(rs.getString("hac_gooffwork_time"));
				ar.setHac_gotowork_time(rs.getString("hac_gotowork_time"));
				ar.setHac_remarks(rs.getString("hac_remarks"));
				ar.setHac_rest_end_time(rs.getString("hac_rest_end_time"));
				ar.setHac_rest_start_time(rs.getString("hac_rest_start_time"));
				ar.setHac_state(rs.getInt("hac_state"));
				ar.setHdr_id(rs.getInt("hdr_id"));
				attendanceRecodeList.add(ar);
			}
			return attendanceRecodeList;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			  BaseDao.getColse(rs, psta, conn);
		}
		return null;
	}

至此就结束了了,这是最简单的一种多数据源的配置方式。不管要连接几个数据源。以此类推就可以。有疑问关注公众号回复消息进行沟通。谢谢大家!!
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值