MyBatis study notes: foundation

MyBatis is a good support for custom SQL queries, stored procedures and persistence framework advanced mapping, eliminating almost all of the settings manually retrieve JDBC code and parameters and the result set. MyBatis can use annotations or XML configuration and mapping, by mapping MyBatis configuration parameters to SQL statements SQL final form of execution, and finally execute SQL mapping results into Java objects returned.

Unlike other ORM frameworks, MyBatis will not be associated with a Java object database, but the Java method associated with the SQL statement. MyBatis provides a mapping engine, declaratively up the results of the mapping object SQL statement. By using XML-like expression language for built-in, SQL statements can be dynamically generated.

First, create an entry in the demo, using maven managing dependencies.

Project after the completion of the preparation of a complete catalog:

First, add a dependency in pom.xml file.

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.18</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j </groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>

    </dependencies>
View Code

First add mybatis-config.xml configuration file is MyBatis core configuration file. In addition to the XML format can also be configured in other ways.

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


    <typeAliases>
        <package name="tk.mybatis.simple.model" />
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="tk/mybatis/simple/mapper/CountryMapper.xml"/>
    </mappers>

</configuration>
View Code

<TypeAliases> alias element disposed below a packet, the so configured, in use when the class name does not need to write part of the package.

<Enviroments> database connection configuration information.

<Mappers> configure the XML configuration file that contains the full class path, the SQL statement and a MyBatis mapping configuration file.

Country create entity classes, and CountryMapper.xml files in the corresponding mapper package. Here is CountryMapper.xml file contents.

<?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="tk.mybatis.simple.mapper.CountryMapper">
    <select id="selectAll" resultType="Country">
        select id, countryname, countrycode from country
    </select>
</mapper>
View Code

If <typeAliases> This attribute is not configured in mybatis-config.xml, then the value of CountryMapper.xml resultType the need to write the full name of the class.

Then write a test class.

public class CountryMapperTest {
    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init() {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testSelectAll() {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            List<Country> countryList = sqlSession.selectList("selectAll");
            printCountryList(countryList);
        }
    }

    private void printCountryList(List<Country> countryList) {
        for (Country country : countryList) {
            System.out.printf("%-4d%4s%4s\n", country.getId(), country.getCountryname(), country.getCountrycode());
        }
    }

}
View Code

In this test class, is loaded first mybatis-config.xml configuration file, and then look for CountryMapper.xml in id = "selectAll" approach by selectList method SqlSession, and execute SQL queries. After the SQL using JDBC MyBatis bottom, the ResultSet query result set is obtained, according to the configuration of resultType mapping the result to set Country type, returns a query result.

This completes the demo, you can get the test results after the operation. 

 

MyBatis real power lies in its mapping statement, and this is its magic lies. When SqlSession calling MyBatis method previously used by a namespace, you first need to use the namespace and method id strings to call the appropriate method. The method of using the interface call will be a lot easier, MyBatis using dynamic Java agent can call the appropriate methods directly through the interface, the interface need not be provided, but do not need to use in the implementation class SqlSession indirect call through a namespace.

The demo will modify the above into the above method to call the appropriate interface. CountryMapper.java add a file as shown below.

Then testSelectAll method in the modified test file.

    @Test
    public void testSelectAll() {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            //List<Country> countryList = sqlSession.selectList("selectAll");
            CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
            List<Country> countryList = mapper.selectAll();
            printCountryList(countryList);
        }
    }
View Code

注释的那一行是旧的方法。新的代码是通过接口调用的。

由于 XML 映射文件较多,依次配置较为麻烦,可以修改 mybatis-config.xml 中 <mappers> 标签内容为如下内容。

    <mappers>

        <!--
        <mapper resource="tk/mybatis/simple/mapper/CountryMapper.xml"/>
        -->

        <package name="tk.mybatis.simple.mapper"/>
    </mappers>
View Code

注释的内容是之前的配置,新的配置会先查找配置的包下所有的接口,循环对接口进行如下操作:

1 判断接口对应的命名空间是否存在,如果存在就抛出异常,不存在就继续;

2 加载接口对应的 XML 映射文件,将接口全限定名转换为路径,例如,将接口 tk.mybatis.simple.mapper.UserMapper 转换为 tk/mybatis/simple/mapper/UserMapper.xml,以 .xml 为后缀搜索 XML 资源,如果找到就解析XML;

3 处理接口中的注解方法。

 

可以发现,XML 中的 select 标签的 id 属性值和定义的接口方法名是一样的。

MyBatis 就是通过这种方式将接口方法和 XML 中定义的 SQL 语句关联到一起的。

以上就是关于 MyBatis 的基本使用。 

 

Guess you like

Origin www.cnblogs.com/colin220/p/11347404.html