每 一 个 MyBatis 的 应 用 程 序 都 以 一 个 SqlSessionFactory 对 象 的 实 例 为 核 心 。SqlSessionFactory本身是由SqlSessionFactoryBuilder创建的,一般而言,在一个应用中,一个数据库只会对应一个SqlSessionFactory,所以一般我们都把SqlSessionFactory定义成单例模式,或通过Spring等进行注入。
SqlSessionFactoryBuilder创建SqlSessionFactory的方法有:
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中构建SqlSessionFactory
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用于定义或导入属性,然后在后面的环境中使用
settings:settings用于设置一些mybatis在运行时的行为方式,具体的设置信息可以查看mybatis的文档
typeAliases:typeAliases是为系统中的Java类型指定一个较短的别名
environments:MyBatis 可以配置多种环境。这会帮助你将 SQL 映射应用于多种数据库之中。
<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(); } }
CREATE TABLE `t_blog` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `content` varchar(255) DEFAULT NULL, `owner` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) )