日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

Mybatis 动态切换数据库

發(fā)布時(shí)間:2023/12/8 数据库 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Mybatis 动态切换数据库 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

mybatis介紹:


每一個(gè)Mybatis的應(yīng)用程序都以一個(gè)SqlSessionFactory對(duì)象的實(shí)例為核心。SqlSessionFactory對(duì)象實(shí)例可以通過SqlSessionFactoryBuilder對(duì)象獲得。SqlSessionFactoryBuilder對(duì)象可以從XML配置文件或從Configuration類的習(xí)慣準(zhǔn)備的實(shí)例中構(gòu)建SqlSessionFactory對(duì)象。


從XML文件中構(gòu)建SqlSessionFactory的實(shí)例非常簡單。這里建議使用類的路徑的資源文件來配置,這樣我們就可以使用任意的Reader實(shí)例,這個(gè)實(shí)例包括有文字形式的文件路徑或URL形式的文件路徑file://來創(chuàng)建。Mybatis包含了一些工具類,稱作為資源,這些工具類包含一些方法,這些方法使得從類路徑或其他位置加載資源文件更加簡單。


<span style="font-size:18px;">String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);</span>
XML的配置文件包含對(duì)MyBatis系統(tǒng)的核心設(shè)置,包含獲取數(shù)據(jù)庫鏈接實(shí)例的數(shù)據(jù)源和決定事物范圍和控制的事物管理器。


<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${driver}"/><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></dataSource></environment></environments><mappers><mapper resource="org/mybatis/example/BlogMapper.xml"/></mappers> </configuration></span>
大家我們今天就可以從這里進(jìn)行入手,大家可以看到,


sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

但是事實(shí)上,SQLSessionFactoryBuilder類負(fù)責(zé)構(gòu)建SqlSessionFactory,并且提供了多個(gè)build的重載方法,丹其實(shí)很多都是在調(diào)用同意簽名的方法,例如public SqlSessionFactory build(InputStream inputStream,String environment,Properties properties),只是由于方法參數(shù)environment和properties都可以為null,所以為了提供調(diào)用的便利性,才提供了下面的三個(gè)方法。


<span style="font-size:18px;">public SqlSessionFactory build(InputStream inputStream) public SqlSessionFactory build(InputStream inputStream, String environment) public SqlSessionFactory build(InputStream inputStream, Properties properties)</span>
真正加載的方法只有三種:


<span style="font-size:18px;">public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) public SqlSessionFactory build(Reader reader, String environment, Properties properties) public SqlSessionFactory build(Configuration config)</span>


建造者模式:


可以看出,配置信息可以以三種形式提供給SqlSessionFactory的build方法,分別是InputStream(字節(jié)流)、Reader(字符流)、Configuration(類),由于字節(jié)流與字符流都屬于讀取配置文件的方式,所以從配置信息的來源就很容易想到創(chuàng)建一個(gè)SqlSessionFactory方式:


(1)讀取XML文件構(gòu)造方式


<span style="font-size:18px;">String resource = "org/mybatis/example/mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream) ;</span>


(2)編程構(gòu)造方式


<span style="font-size:18px;">DataSource dataSource = BlogDataSourceFactory.getBlogDataSource(); TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); Configuration configuration = new Configuration(environment); configuration.addMapper(BlogMapper.class); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration) ;</span>
下面先來分析XML文件構(gòu)建方式的build方法的源碼:


<span style="font-size:18px;">public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {try {XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);return build(parser.parse());} catch (Exception e) {throw ExceptionFactory.wrapException("Error building SqlSession.", e);} finally {ErrorContext.instance().reset();try {inputStream.close();} catch (IOException e) {// Intentionally ignore. Prefer previous error.}}}</span>

通過上面的幾行代碼,就能看出基于XML文件的這種構(gòu)造方式,通過XML讀取信息的工作之后,也是構(gòu)造出Configuration對(duì)象之后,再繼續(xù)進(jìn)行SqlSessionFactory的構(gòu)建工作的,只是多了些XML的解析工作,所以我們只需要單鉤植入,直接分析變成構(gòu)造方式的代碼就可以了,或者是直接分析build(Parser.parse())這句代碼


<span style="font-size:18px;"> public SqlSessionFactory build(Configuration config) {return new DefaultSqlSessionFactory(config);}</span>
其實(shí)這么看來SqlSessionFactory在mybatis的默認(rèn)實(shí)現(xiàn)類為org.apache.ibatis.session.defaults.DefaultSqlSessionFactory , 其構(gòu)造過程主要是注入了Configuration的實(shí)例對(duì)象,Configuration的實(shí)例對(duì)象即可通過解析xml配置文件產(chǎn)生,也可能通過代碼直接構(gòu)造。


以上代碼使用了一個(gè)設(shè)計(jì)模式:建設(shè)者模式(Builder),SqlSessionFactoryBuilder扮演具體的建造者,Configuration類則負(fù)責(zé)建造的細(xì)節(jié)工作,SqlSession則是建造出來的產(chǎn)品。


看一下類圖和創(chuàng)建者模式的基本形態(tài)圖:






代碼實(shí)現(xiàn)Mybatis動(dòng)態(tài)切換數(shù)據(jù)庫:


目錄結(jié)構(gòu):




Goods:


<span style="font-size:18px;">package com.csdn.kane.domain;import java.sql.Timestamp;public class Goods {private int id; private int categoryId; private String name; private float price; private String description; private int acount; private Timestamp updateTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCategoryId() { return categoryId; } public void setCategoryId(int categoryId) { this.categoryId = categoryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getAcount() { return acount; } public void setAcount(int acount) { this.acount = acount; } public Timestamp getUpdateTime() { return updateTime; } public void setUpdateTime(Timestamp updateTime) { this.updateTime = updateTime; } } </span>

GoodsMapper:


<span style="font-size:18px;">package com.csdn.kane.dao;import org.apache.ibatis.annotations.Select;import com.csdn.kane.domain.Goods;public interface GoodsMapper {@Select("SELECT * FROM Goods WHERE id=#{id}") public Goods selectGoods(int id); } </span>
applicationContext.xml:


<span style="font-size:18px;"><?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 alias="Goods" type="com.csdn.kane.domain.Goods"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /></dataSource> </environment> </environments> <mappers> <mapper class="com.csdn.kane.dao.GoodsMapper"/> </mappers> </configuration> </span>
TestMybatis:


<span style="font-size:18px;">package com.csdn.kane.test;import java.io.IOException; import java.io.InputStream; import java.util.Properties;import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.csdn.kane.dao.GoodsMapper; import com.csdn.kane.domain.Goods;public class TestMybitas { public static void main(String[] args) throws IOException { //最基本的mybitas示例方法 TestMybitas.testMethod(); } public static void testMethod() throws IOException{ String resource = "applicationContext.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); Properties properties = new Properties();properties.setProperty("jdbc.driver", "com.mysql.jdbc.Driver");properties.setProperty("jdbc.url","jdbc:mysql://localhost:3306/qmxtest1?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true"); properties.setProperty("jdbc.username", "root");properties.setProperty("jdbc.password", "root");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,properties); SqlSession session = sqlSessionFactory.openSession(); try { GoodsMapper mapper = session.getMapper(GoodsMapper.class); Goods goods = mapper.selectGoods(1); System.out.println("good description:"+goods.getDescription()); } finally { session.close(); } } } </span>
這里傳入的Property是咱們需要訪問的數(shù)據(jù)庫,當(dāng)然,后面的參數(shù)是可以作為變量進(jìn)行傳遞的。













總結(jié)

以上是生活随笔為你收集整理的Mybatis 动态切换数据库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。