每 一 個 MyBatis 的 應 用 程 序 都 以 一 個 SqlSessionFactory 對 象 的 實 例 爲 核 心 。SqlSessionFactory自己是由SqlSessionFactoryBuilder建立的,通常而言,在一個應用中,一個數據庫只會對應一個SqlSessionFactory,因此通常咱們都把SqlSessionFactory定義成單例模式,或經過Spring等進行注入。java
SqlSessionFactoryBuilder建立SqlSessionFactory的方法有:sql
SqlSessionFactory build(InputStream inputStream) SqlSessionFactory build(InputStream inputStream, String environment) SqlSessionFactory build(InputStream inputStream, Properties properties) SqlSessionFactory build(InputStream inputStream, String env, Properties props) SqlSessionFactory build(Configuration config)
這些方法主要設計到的參數有InputStream,environment,properties,其中InputStream是從配置文件中獲取的一個輸入流;environment表示在配置文件裏面配置的衆多的environment中,當前要使用的是哪個environment,包括數據源和事務,缺省則使用默認的environment;使用properties,MyBatis則會加載對應的屬性或文件,它們能夠在配置文件中使用。 數據庫
從XML中構建SqlSessionFactoryapache
private static SqlSessionFactory sqlSessionFactory = null; static { try { InputStream is = Resources.getResourceAsStream("config/mybatis_config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; }
下面講講配置文件的基本結構:安全
mybatis的配置文件通常包括以下幾個部分:服務器
properties:properties用於定義或導入屬性,而後在後面的環境中使用session
settings:settings用於設置一些mybatis在運行時的行爲方式,具體的設置信息能夠查看mybatis的文檔mybatis
typeAliases:typeAliases是爲系統中的Java類型指定一個較短的別名app
environments:MyBatis 能夠配置多種環境。這會幫助你將 SQL 映射應用於多種數據庫之中。ide
<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>
因爲MyBatis能夠配置多個environment,因此能夠在建立SqlSessionFactory的時候指定具體的環境來建立特定的環境下的SqlSessionFactory, 不指定則使用默認的環境。
transactionManager
在 MyBatis 中有兩種事務管理器類型(也就是 type=」[JDBC|MANAGED]」):
dataSource
dataSource 元素使用基本的 JDBC 數據源接口來配置 JDBC 鏈接對象的資源。
有三種內建的數據源類型(也就是 type=」???」):
UNPOOLED – 這個數據源的實現是每次被請求時簡單打開和關閉鏈接。它有一點慢, 這是對簡單應用程序的一個很好的選擇, 由於它不須要及時的可用鏈接。 不一樣的數據庫對這 個的表現也是不同的, 因此對某些數據庫來講配置數據源並不重要, 這個配置也是閒置的。 UNPOOLED 類型的數據源僅僅用來配置如下 5 種屬性:
做爲可選項,你能夠傳遞數據庫驅動的屬性。要這樣作,屬性的前綴是以「driver.」開 頭的,例如:
這 樣 就 會 傳 遞 以 值 「 UTF8 」 來 傳 遞 屬 性 「 encoding 」, 它 是 通 過 DriverManager.getConnection(url,driverProperties)方法傳遞給數據庫驅動。
POOLED – 這是 JDBC 鏈接對象的數據源鏈接池的實現,用來避免建立新的鏈接實例 時必要的初始鏈接和認證時間。這是一種當前 Web 應用程序用來快速響應請求很流行的方 法。
除了上述(UNPOOLED)的屬性以外,還有不少屬性能夠用來配置 POOLED 數據源:
JNDI – 這個數據源的實現是爲了使用如 Spring 或應用服務器這類的容器, 容器能夠集 中或在外部配置數據源,而後放置一個 JNDI 上下文的引用。這個數據源配置只須要兩個屬 性:
<mappers> <mapper resource="com/tiantian/mybatis/model/BlogMapper.xml"/> </mappers>
<?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> <properties resource="config/jdbc.properties"></properties> <typeAliases> <typeAlias alias="Blog" type="com.tiantian.mybatis.model.Blog"/> </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 resource="com/tiantian/mybatis/model/BlogMapper.xml"/> </mappers> </configuration>
SqlSession session = sqlSessionFactory.openSession();
SqlSession openSession() SqlSession openSession(boolean autoCommit) SqlSession openSession(Connection connection) SqlSession openSession(TransactionIsolationLevel level) SqlSession openSession(ExecutorType execType,TransactionIsolationLevel level) SqlSession openSession(ExecutorType execType) SqlSession openSession(ExecutorType execType, boolean autoCommit) SqlSession openSession(ExecutorType execType, Connection connection) Configuration getConfiguration();
import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Util { private static SqlSessionFactory sqlSessionFactory = null; static { try { InputStream is = Resources.getResourceAsStream("config/mybatis_config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } }
<?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> <properties resource="config/jdbc.properties"></properties> <typeAliases> <typeAlias alias="Blog" type="com.tiantian.mybatis.model.Blog"/> </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 resource="com/tiantian/mybatis/model/BlogMapper.xml"/> </mappers> </configuration>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.tiantian.mybatis.model.BlogMapper"> <!-- 新增記錄 --> <insert id="insertBlog" parameterType="Blog"> insert into t_blog(title,content,owner) values(#{title},#{content},#{owner}) </insert> <!-- 查詢單條記錄 --> <select id="selectBlog" parameterType="int" resultType="Blog"> select * from t_blog where id = #{id} </select> <!-- 修改記錄 --> <update id="updateBlog" parameterType="Blog"> update t_blog set title = #{title},content = #{content},owner = #{owner} where id = #{id} </update> <!-- 查詢全部記錄,查詢多條記錄即返回結果是一個集合的時候,resultType不是集合類型,而是集合所包含的類型 --> <select id="selectAll" resultType="Blog"> select * from t_blog </select> <!-- 模糊查詢 --> <select id="fuzzyQuery" resultType="Blog" parameterType="java.lang.String"> select * from t_blog where title like "%"#{title}"%" </select> <!-- 刪除記錄 --> <delete id="deleteBlog" parameterType="int"> delete from t_blog where id = #{id} </delete> </mapper>
package com.tiantian.mybatis.model; public class Blog { private int id; private String title; private String content; private String owner; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } @Override public String toString() { return "id: " + id + ", title: " + title + ", content: " + content + ", owner: " + owner; } }
package com.tiantian.mybatis.model; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; /** * 如下的操做1都是把SQL寫在配置文件裏面的,而操做2都是直接用註解標明要執行的SQL語句 * 由於該Mapper的全名跟BlogMapper.xml文件裏面的namespace是同樣的,因此不能在這裏面 * 用註解定義一個與BlogMapper.xml文件裏面同名的映射 * @author andy * */ public interface BlogMapper { public Blog selectBlog(int id); @Select("select * from t_blog where id = #{id}") public Blog selectBlog2(int id); public void insertBlog(Blog blog); @Insert("insert into t_blog(title,content,owner) values(#{title},#{content},#{owner})") public void insertBlog2(Blog blog); public void updateBlog(Blog blog); @Update("update t_blog set title=#{title},content=#{content},owner=#{owner} where id=#{id}") public void updateBlog2(Blog blog); public void deleteBlog(int id); @Delete("delete from t_blog where id = #{id}") public void deleteBlog2(int id); public List<Blog> selectAll(); @Select("select * from t_blog") public List<Blog> selectAll2(); public List<Blog> fuzzyQuery(String title); @Select("select * from t_blog where title like \"%\"#{title}\"%\"") public List<Blog> fuzzyQuery2(String title); }
package com.tiantian.mybatis.test; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.tiantian.mybatis.model.Blog; import com.tiantian.mybatis.util.Util; /** * 該系列操做是經過把SQL寫在配置文件裏面, * 而後利用SqlSession進行操做的 * @author andy * */ public class Test1 { /** * 新增記錄 */ @Test public void testInsertBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); Blog blog = new Blog(); blog.setTitle("中國人"); blog.setContent("五千年的風和雨啊藏了多少夢"); blog.setOwner("每天"); session.insert("com.tiantian.mybatis.model.BlogMapper.insertBlog", blog); session.commit(); session.close(); } /** * 查詢單條記錄 */ @Test public void testSelectOne() { SqlSession session = Util.getSqlSessionFactory().openSession(); Blog blog = (Blog)session.selectOne("com.tiantian.mybatis.model.BlogMapper.selectBlog", 8); System.out.println(blog); session.close(); } /** * 修改記錄 */ @Test public void testUpdateBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); Blog blog = new Blog(); blog.setId(7);//須要修改的Blog的id blog.setTitle("中國人2");//修改Title blog.setContent("黃色的臉,黑色的眼,不變是笑容");//修改Content blog.setOwner("每天2");//修改Owner session.update("com.tiantian.mybatis.model.BlogMapper.updateBlog", blog); session.commit(); session.close(); } /** * 查詢全部的記錄 */ @Test public void testSelectAll() { SqlSession session = Util.getSqlSessionFactory().openSession(); List<Blog> blogs = session.selectList("com.tiantian.mybatis.model.BlogMapper.selectAll"); for (Blog blog:blogs) System.out.println(blog); session.close(); } /** * 模糊查詢 */ @Test public void testFuzzyQuery() { SqlSession session = Util.getSqlSessionFactory().openSession(); String title = "中國"; List<Blog> blogs = session.selectList("com.tiantian.mybatis.model.BlogMapper.fuzzyQuery", title); for (Blog blog:blogs) System.out.println(blog); session.close(); } /** * 刪除記錄 */ @Test public void testDeleteBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); session.delete("com.tiantian.mybatis.model.BlogMapper.deleteBlog", 8); session.commit(); session.close(); } }
package com.tiantian.mybatis.test; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.tiantian.mybatis.model.Blog; import com.tiantian.mybatis.model.BlogMapper; import com.tiantian.mybatis.util.Util; /** * 該系列操做是將SQL語句寫在配置文件裏面, * 而後經過對應Mapper接口來進行操做的 * @author andy * */ public class Test2 { /** * 新增記錄 */ @Test public void testInsertBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); Blog blog = new Blog(); blog.setTitle("中國人"); blog.setContent("五千年的風和雨啊藏了多少夢"); blog.setOwner("每天"); BlogMapper blogMapper = session.getMapper(BlogMapper.class); blogMapper.insertBlog(blog); session.commit(); session.close(); } /** * 查詢單條記錄 */ @Test public void testSelectOne() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); Blog blog = blogMapper.selectBlog(7); System.out.println(blog); session.close(); } /** * 修改記錄 */ @Test public void testUpdateBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); Blog blog = new Blog(); blog.setId(9);// 須要修改的Blog的id blog.setTitle("中國人2");// 修改Title blog.setContent("黃色的臉,黑色的眼,不變是笑容");// 修改Content blog.setOwner("每天2");// 修改Owner BlogMapper blogMapper = session.getMapper(BlogMapper.class); blogMapper.updateBlog(blog); session.commit(); session.close(); } /** * 查詢全部記錄 */ @Test public void testSelectAll() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); List<Blog> blogs = blogMapper.selectAll(); for (Blog blog : blogs) System.out.println(blog); session.close(); } /** * 模糊查詢 */ @Test public void testFuzzyQuery() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); String title = "中國"; List<Blog> blogs = blogMapper.fuzzyQuery(title); for (Blog blog : blogs) System.out.println(blog); session.close(); } /** * 刪除記錄 */ @Test public void testDeleteBlog() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); blogMapper.deleteBlog(10); session.commit(); session.close(); } }
package com.tiantian.mybatis.test; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.tiantian.mybatis.model.Blog; import com.tiantian.mybatis.model.BlogMapper; import com.tiantian.mybatis.util.Util; /** * 該系列操做是利用Mapper接口來進行的 * ,然而其相應的SQL語句是經過對應的 * 註解Annotation在Mapper中對應的方法上定義的 * @author andy * */ public class Test3 { /** * 新增記錄 */ @Test public void testInsert() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); Blog blog = new Blog(); blog.setTitle("title2"); blog.setContent("content2"); blog.setOwner("owner2"); blogMapper.insertBlog2(blog); session.commit(); session.close(); } /** * 查找單條記錄 */ @Test public void testSelectOne() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); Blog blog = blogMapper.selectBlog2(1); System.out.println(blog); session.close(); } /** * 查找多條記錄,返回結果爲一集合 */ @Test public void testSelectAll() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); List<Blog> blogs = blogMapper.selectAll2(); for (Blog blog:blogs) System.out.println(blog); session.close(); } /** * 修改某條記錄 */ @Test public void testUpdate() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); Blog blog = new Blog(); blog.setId(3); blog.setTitle("title3"); blog.setContent("content3"); blog.setOwner("owner3"); blogMapper.updateBlog2(blog); session.commit(); session.close(); } /** * 刪除記錄 */ @Test public void testDelete() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); blogMapper.deleteBlog2(5); session.commit(); session.close(); } @Test public void testFuzzyQuery() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); List<Blog> blogs = blogMapper.fuzzyQuery2("中國"); for (Blog blog:blogs) System.out.println(blog); session.close(); } }