mybatis introduce simple entry

mybatis entry


Brief introduction

What is mybatis?

MyBatis is an excellent persistence framework that supports custom SQL, stored procedures and advanced mappings. MyBatis avoids almost all JDBC code and manual setting parameters and obtaining the result set. MyBatis can use simple XML configuration and mapping annotations or native types, interfaces and Java POJO (Plain Old Java Objects, plain old Java object) is recorded in the database.

Core sqlSessionFactory

mybatis core is sqlSessionFactory instance, which can be obtained by SqlSessionFactoryBuilder, SqlSessionFactoryBuilder is to get through the xml file.

  • Resource tools constructed by Mybatis band sqlSessionFactory

    String resource = "org/mybatis/example/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  • xml file core configuration, including the following DataSource and TransactionManager (Transaction Manager)

    <?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>

    Of course also be arranged by way of a non-xml mybatis, it is to use some of the classes provided by mybatis java code configuration, since many complex mapping so as nested combined also with xml configuration, especially now that many of the scenes with applicalion springboot. yml configuration, where the configuration of Java code that is not described in detail here.

SqlSession get from the SqlSessionFactory

With SqlSessionFactory, we must get the data we want to find out sqlsession final investigation. First adopted sqlsessionFactory to sqlSession, and then obtain the corresponding mapper by sqlSession, the corresponding data corresponding mapper can check the future will slowly unfold this point. The following look at the process of code:

try (SqlSession session = sqlSessionFactory.openSession()) {
  BlogMapper mapper = session.getMapper(BlogMapper.class);
  Blog blog = mapper.selectBlog(101);
}

These are the simple entry mybatis of the future will be to expand the implementation process and the characteristics of sql mybatis on this basis.

Guess you like

Origin www.cnblogs.com/yixinli/p/11616249.html