Mybaits技术如今不少公司都在使用,它提供了简单的API能够快速进行数据库操做,因此无论是本身作系统仍是找工做都有必要了解一下。sql
学习一门技术若是是入门的话要么买书要么就是阅读官方的文档,并且官方的文档全且及时更新,因此建议阅读官方文档,本系列入门教程其实就是官方文档的简易汉化版(哈哈)数据库
Mybaits应用是一个SqlSessionFactory的实例,而SqlSessionFactory时经过SqlSessionFactoryBuilder得到的。SqlSessionFactoryBuilder可使用xml配置文件或者一些预先准备配置类实例化一个SqlSessionFactory。session
经过xml配置得到一个SqlSessionFactory实例十分简单,推荐你使用类路径,可是你也可使用任何的InputStream实例(简单的讲,你把读取的文件放到InputStream流里面就行,文件随你放哪里),这里注意一下Mybaitsmybatis
有一个工具类叫Resources,他提供了不少简单的方法获取资源。app
xml配置文件包含mybaits系统的核心,包括数据库连接、事物控制等 这里咱们先贴一个简单的代码工具
1 String resource ="cn/dota/uc/test/cfg.xml"; 2 InputStream is = Resources.getResourceAsStream(resource); 3 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value=""/>
<property name="url" value=""/>
<property name="username" value=""/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/xxx/xxx/BlogMapper.xml" />
</mappers>
</configuration>
注意图中标红的须要制定为类路径学习
还有一种方式时经过Configuration类设置属性,这种方式侵入了代码你们能够本身看这段的文档,本系列就不介绍了ui
经过SqlSession你就能够开始操做数据库了以下代码url
如今版本的Mybatis有了新的方式可使用接口进行开发以下spa
一种实在BlogMapper.xml中指定sql语句
<?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="cn.dota.uc.test.BlogMapper"> <select id="selectBlog" resultType="cn.dota.uc.test.Blog"> select * from Blog where id = #{id} </select> </mapper>
SqlSession session = sqlSessionFactory.openSession(); try{ Blog blog = session.selectOne("cn.dota.uc.test.BlogMapper.selectBlog", 100); } finally{ session.close(); }
还有一种就是使用接口,首先咱们要定义一个接口BlogMapper,代码以下
<?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="cn.dota.uc.test.BlogMapper">
</mapper>
SqlSession session = sqlSessionFactory.openSession(); try{ BlogMapper mapper = session.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(101); } finally{ session.close(); }
这种方式须要注意的就是配置文件的namespace 中 value必须和 接口相对应
public interface BlogMapper { @Select("SELECT * FROM blog where id = #{id}") Blog selectBlog(int id); }
因此简单来讲 Mybatis开发的步骤就是
SqlSessionFactoryBuilder 仅仅用于创造sqlSessionFactory 因此可使用完丢弃
SqlSessionFactory 单例和静态类是最好的方式
SqlSession 局部做用域就能够了