Mybatis 3 | reference documentation

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all of the JDBC code and the work of setting parameters and fetching result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) to records in the database via simple XML or annotations.

Mybatis environment configuration

Import the package required by Mybatis through Maven’s POM. XML file

Add the following code to its
tag

 <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1 track of</version>
 </dependency>
Copy the code

In 2.src/main/resourcesUnder the newmybatis-config.xmlfile

And declare the XML file and the DTD file of config

    
      
    <! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

Copy the code

In 3.mybatis-config.xmlIn the file<configuration></configuration>To configure the database

<configuration>
    <settings>
<! SQL > select goods_ID from goods_ID and goodsId from goods_ID
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <! -- Set the default database to point to -->
    <environments default="dev">
        <environment id="dev">
            <! Commit /rollback -->
            <transactionManager type="JDBC"></transactionManager>
            <! Mysql > manage database connections by pool
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/babytun? useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
</configuration>
Copy the code

4. Use SqlSessionFactory to build an SqlSession instance

Each MyBatis application is built around an instance of the SqlSessionFactory. An instance of SqlSessionFactory can be obtained from SqlSessionFactoryBuilder. SqlSessionFactoryBuilder, on the other hand, can build an SqlSessionFactory instance from an XML Configuration file or a pre-configured Configuration instance.

Building an instance of SqlSessionFactory from an XML file is straightforward, and it is recommended to use a resource file under the classpath for configuration. But you can also use an arbitrary instance of an InputStream, such as an InputStream constructed from a file path string or a file:// URL. MyBatis includes a utility class called Resources, which contains utility methods that make it easier to load resource files from the classpath or elsewhere. Typically SqlSession is globally unique, reducing duplicate code through the MybatisUtils utility class

public class MybatisUtils {
    // static is a class, not an object, that is globally unique
    private static SqlSessionFactory sqlSessionFactory = null ;
    // Use static blocks to initialize class SqlSessionFactory
    static {
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader) ;
        } catch (IOException e) {
            e.printStackTrace();
            // An exception occurred during initialization
            throw  newExceptionInInitializerError(e) ; }}/** * Create a new SQLSession object *@returnSqlsession object * */

    public static SqlSession openSession(a){
        return sqlSessionFactory.openSession() ;
    }

    public static void closeSession(SqlSession sqlSession){
        if(sqlSession ! =null){ sqlSession.close(); }}}Copy the code

5. Perform operations on the database using SqlSession

Create the entity class corresponding to the database table to be manipulated under the Entity package (you must use camel name and set the GET and set methods), and create the Mappers directory under the Resources directory. In the mappers directory, create an XML file with the same name as the entity class, and then make an XML declaration and mapperd on it Td file declaration (note the difference with the DTD file declaration of mybatis-config.xml)


      
<! DOCTYPEmapper
       PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
Copy the code

The mapping of this entity to the database is then introduced in the mybatis-config.xml file. That is, add the mapping XML file path to its
tag

 <mappers>
       <mapper resource="mappers/goods.xml" />
       <mapper resource="mappers/goods_detail.xml" />
 </mappers>
Copy the code

If the database column field name is multi-word and concatenated with “_”, you need to enable the camel name conversion in the < Configuration >
TAB, so that Mybatis automatically complete the mapping.

 <settings>
<! SQL > select goods_ID from goods_ID and goodsId from goods_ID
       <setting name="mapUnderscoreToCamelCase" value="true"/>
  </settings>
Copy the code

At this point, the configuration required for MyBatis is complete.