mybatis介紹:
每一個Mybatis的應用程序都以一個SqlSessionFactory對象的實例為核心。SqlSessionFactory對象實例可以通過SqlSessionFactoryBuilder對象獲得。SqlSessionFactoryBuilder對象可以從XML配置文件或從Configuration類的習慣準備的實例中構建SqlSessionFactory對象。
從XML文件中構建SqlSessionFactory的實例非常簡單。這里建議使用類的路徑的資源文件來配置,這樣我們就可以使用任意的Reader實例,這個實例包括有文字形式的文件路徑或URL形式的文件路徑file://來創建。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的配置文件包含對MyBatis系統的核心設置,包含獲取數據庫鏈接實例的數據源和決定事物范圍和控制的事物管理器。
<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>
大家我們今天就可以從這里進行入手,大家可以看到,
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
但是事實上,SQLSessionFactoryBuilder類負責構建SqlSessionFactory,并且提供了多個build的重載方法,丹其實很多都是在調用同意簽名的方法,例如public SqlSessionFactory build(InputStream inputStream,String environment,Properties properties),只是由于方法參數environment和properties都可以為null,所以為了提供調用的便利性,才提供了下面的三個方法。
<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(字節流)、Reader(字符流)、Configuration(類),由于字節流與字符流都屬于讀取配置文件的方式,所以從配置信息的來源就很容易想到創建一個SqlSessionFactory方式:
(1)讀取XML文件構造方式
<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)編程構造方式
<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文件構建方式的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文件的這種構造方式,通過XML讀取信息的工作之后,也是構造出Configuration對象之后,再繼續進行SqlSessionFactory的構建工作的,只是多了些XML的解析工作,所以我們只需要單鉤植入,直接分析變成構造方式的代碼就可以了,或者是直接分析build(Parser.parse())這句代碼
<span style="font-size:18px;"> public SqlSessionFactory build(Configuration config) {return new DefaultSqlSessionFactory(config);}</span>
其實這么看來SqlSessionFactory在mybatis的默認實現類為org.apache.ibatis.session.defaults.DefaultSqlSessionFactory , 其構造過程主要是注入了Configuration的實例對象,Configuration的實例對象即可通過解析xml配置文件產生,也可能通過代碼直接構造。
以上代碼使用了一個設計模式:建設者模式(Builder),SqlSessionFactoryBuilder扮演具體的建造者,Configuration類則負責建造的細節工作,SqlSession則是建造出來的產品。
看一下類圖和創建者模式的基本形態圖:
代碼實現Mybatis動態切換數據庫:
目錄結構:
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是咱們需要訪問的數據庫,當然,后面的參數是可以作為變量進行傳遞的。
總結
以上是生活随笔為你收集整理的Mybatis 动态切换数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。