以爲查看源代碼確實是一個學習的一種方法 由於不少時候別人把最核心的代碼給咱們都封裝好了 咱們直接能夠來拿使用 不少時候本身也會問 爲何經過這個方法就能夠獲得我以爲就是一顆好奇心吧 我算了算 就這三個部分也花了幾個小時的時間去琢磨 可是感受值了,我以爲對mybaties的原理更加清晰了 java
學了mybaties也有一段時間了 今天抽空來聊聊mybaties是如何來操做數據庫的 它爲何可以方便咱們不用再去關注如何建立鏈接編寫預編譯語句 它又是如何實現的呢?咱們都知道 要操做數據庫數據庫 必須先要有數據源 執行語句 還要有操做mysql
1.數據源 是用來鏈接數據庫的 他是如何獲取到數據庫的鏈接的呢 咱們知道mybatais有一個核心配置文件mybatis-config.xml 而這個文件裏面 裏面有不少數據庫鏈接信息sql
接下里咱們來看一下源碼是如何獲取到數據源的數據庫
org.apache.ibatis.session.SqlSessionFactoryBuilder.build(InputStream)apache
org.apache.ibatis.session.SqlSessionFactoryBuilder.build(InputStream, String, Properties)安全
org.apache.ibatis.builder.xml.XMLConfigBuilder.XMLConfigBuilder(InputStream, String, Properties)session
org.apache.ibatis.builder.xml.XMLConfigBuilder.parse()mybatis
org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XNode)app
最後咱們能夠經過parseConfiguration(XNode)這個方法就能夠獲得 鏈接數據源的信息 學習
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 6 <configuration> 7 <!-- 配置環境信息,即數據源信息 --> 8 <environments default="d1"> 9 <environment id="d1"> 10 <!-- 配置事務管理器 --> 11 <transactionManager type="JDBC" /> 12 <!-- 配置數據源以及數據庫鏈接信息 --> 13 <dataSource type="POOLED"> 14 <property name="driver" value="com.mysql.jdbc.Driver" /> 15 <property name="url" 16 value="jdbc:mysql://localhost:3306/fresh?characterEncoding=UTF-8" /> 17 <property name="username" value="root" /> 18 <property name="password" value="root" /> 19 </dataSource> 20 </environment> 21 </environments> 22 <!-- 關聯隱射文件 --> 23 <mappers> 24 <mapper resource="com/newroad/dao/StudentMapper.xml" /> 25 </mappers> 26 </configuration> 27
2.執行語句 首先來了解如下這四種語句 那麼他們又是如何執行的呢
org.apache.ibatis.session.SqlSession. (Class<T>)
org.apache.ibatis.session.Configuration.getMapper(Class<T>, SqlSession)
org.apache.ibatis.binding.MapperRegistry.getMapper(Class<T>, SqlSession)
org.apache.ibatis.binding.MapperProxyFactory.newInstance(SqlSession)
org.apache.ibatis.binding.MapperProxy.MapperProxy(SqlSession, Class, Map)
java.lang.reflect.Method.invoke(Object, Object...)
org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(Method)
org.apache.ibatis.binding.MapperMethod.execute(SqlSession, Object[])
DDL | DML | DQL | DCL |
---|---|---|---|
數據定義語言 | 數據操縱語言 | 數據查詢語言 | 數據控制語言,定義訪問權限、取消訪問權限,安全設置 |
create、drop、alter | insert、update、delete | select | grant |
3.操做
org.apache.ibatis.session.defaults.DefaultSqlSessionFactory.openSession()