1、Mybatis的作用
Mybatis的主要作用可以用下面的一段代码解释
- Class.forName("com.mysql.jdbc.Driver");
- Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
- String sql = "select * from tab_user where id= ?";
- // prepare sql
- PreparedStatement pstmt = connection.prepareStatement(sql);
- // set parameter
- pstmt.setInt(1, 18);
- ResultSet rs = pstmt.executeQuery();
- User user = null;
- // extract resultset
- while (rs.next()) {
- user = new User(rs.getInt("id"), rs.getString("name"));
- System.out.println(user);
- }
- // release resource
- rs.close();
- pstmt.close();
- connection.close();
2、Mybatis的demo
Mysql数据库创建表tab_user
- CREATE TABLE `tab_user` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(100) NOT NULL,
- `birthday` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- PRIMARY KEY (`id`)
- );
- INSERT INTO `tab_user` VALUES ('18', 'jack', '2017-01-24 22:15:03');
新建demo工程在classpath下新建config/mybatis-config.xml配置文件和config/mapper/UserMapper.xml映射文件
mybatis-config.xml文件内容
- <?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="com.mysql.jdbc.Driver" />
- <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
- <property name="username" value="root" />
- <property name="password" value="root" />
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="config/mapper/UserMapper.xml" />
- </mappers>
- </configuration>
UserMapper.xml文件内容
- <?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="UserMapper">
- <select id="selectUser" parameterType="int" resultType="com.fit.bean.User">
- select * from tab_user where id = #{id}
- </select>
- </mapper>
Java代码(引入依赖jar包:mysql-connector.jar和mybatis-3.3.x.jar)
- SqlSession sqlSession = null;
- try {
- String resource = "config/mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //start
- sqlSession = sqlSessionFactory.openSession();
- User user = sqlSession.selectOne("UserMapper.selectUser", 18); //query db
- System.out.println(user);
- user = sqlSession.selectOne("UserMapper.selectUser", 18);
- System.out.println(user);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (sqlSession != null)
- sqlSession.close(); //release resource
- }
实体类User.java
- import java.io.Serializable;
- public class User implements Serializable {
- private static final long serialVersionUID = 1L;
- private int id;
- private String name;
- public User() {
- super();
- }
- public User(int id, String name) {
- super();
- this.id = id;
- this.name = name;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- @Override
- public String toString() {
- return "{id=" + id + ", name=" + name + "}";
- }
- }
demo工程结构
正常情况下就可以输出一个user对象信息
3、Mybatis执行过程分析
3.1启动
- String resource = "config/mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
上面的demo可以看出实现过程是先读取mybatis配置文件,通过SqlSessionFactoryBuilder基于文件输入流创建SqlSessionFactory。
具体实现过程:
SqlSessionFactoryBuiler的build(inputStream)最终调用了下面的方法
- 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.
- }
- }
- }
XMLConfigBuilder的parse()方法主要就是解析mybatis-config.xml,通过configuraton根节点具体解析的属性如下
- private void parseConfiguration(XNode root) {
- try {
- //issue #117 read properties first
- propertiesElement(root.evalNode("properties"));
- Properties settings = settingsAsProperties(root.evalNode("settings"));
- loadCustomVfs(settings);
- typeAliasesElement(root.evalNode("typeAliases"));
- pluginElement(root.evalNode("plugins"));
- objectFactoryElement(root.evalNode("objectFactory"));
- objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
- reflectionFactoryElement(root.evalNode("reflectionFactory"));
- settingsElement(settings);
- // read it after objectFactory and objectWrapperFactory issue #631
- environmentsElement(root.evalNode("environments"));
- databaseIdProviderElement(root.evalNode("databaseIdProvider"));
- typeHandlerElement(root.evalNode("typeHandlers"));
- mapperElement(root.evalNode("mappers"));
- } catch (Exception e) {
- throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
- }
- }
根据配置文件生成Configuration对象,这个对象非常重要,是全局的配置信息,其中比较重要的包括根据plugin标签配置生成用户配置的自定义插件(比如用户可以实现mysql分页插件)、全局的setting属性配置(二级缓存配置等)、mapper映射文件信息读取。
最后用生成的configuration对象生成DefaultSqlSessionFactory对象
- public SqlSessionFactory build(Configuration config) {
- return new DefaultSqlSessionFactory(config);
- }
3.2执行增删改查
- sqlSession = sqlSessionFactory.openSession();
- User user = sqlSession.selectOne("UserMapper.selectUser", 18);
通过3.1已经获取了SqlSessionFactory,通过SqlSessionFactory创建SqlSession,Mybatis对数据库的操作主要也就是由SqlSession接口定义,由DefaultSqlSession实现。
首先看一下SqlSession接口的定义(定义了增删改查等基本数据库操作和一些事务的操作)
//TODO:解析sql文件、根据入参赋值预编译sql、处理结果集
3.3释放资源
- sqlSession.close();