Loading

mybatis启动过程01

官方简介

mybatis是一款持久层框架(persistence framework),支持自定义sql,存储过程以及高级映射。由此避免了繁琐的代码。通过xml或注解的形式来映射数据。

mybatis核心类sqlSessionFactory

sqlSessionFactory是mybatis构建映射的基础,sqlSessionFactory通过SqlSessionFactoryBuilder 中的build方法可以获得,SqlSessionFactoryBuilder 接收预先设置好的Configuration 来创建一个sqlSessionFactory实例。

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

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="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

下面来看看一条普通的查询在mybatis中是怎样完成的:

<?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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

这条查询很简单,在命名空间"org.mybatis.example.BlogMapper"中定义了一个名为"selectBlog"的映射语句,返回类型为"Blog",sql具体内容为传入一个Blog中的id,查出对应的Blog,返回一个Blog对象。

这条查询是是这样被实现的:
try (SqlSession session = sqlSessionFactory.openSession()) {
  Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
}

首先调用sqlSessionFactory的openSession拿到一个sqlSession对象,sqlSession提供了数据库执行所有操作需要的所有方法,所以可以通过sqlSession对象来执行已经映射的sql语句。

下面是平时比较常见的版本:
try (SqlSession session = sqlSessionFactory.openSession()) {
  BlogMapper mapper = session.getMapper(BlogMapper.class);
  Blog blog = mapper.selectBlog(101);
}

这种方式更加的清晰明了。

posted @ 2021-01-26 10:50  hh的小角落  阅读(61)  评论(0)    收藏  举报