Share knowledge, not yourself.

preface

In the previous section, we created a myBatis_Quick_start project that implements the most basic data manipulation and core configuration of MyBatis. Test classes are also created to prove that the code is correct. The implementation in the previous section does simplify operations compared to JDBC operations, but it still doesn’t have the desired effect. So in this section we will continue to learn MyBatis configuration and implementation of more advanced usage, let our code further upgrade.

Interface and dynamic proxy to achieve data operation

Interface plus dynamic proxy is the main way in our work. Based on this approach and MyBatis excellent encapsulation ideas. Let’s write code without having to worry about locating SQL. Further reduce hard coding in code. The implementation of Mapper interface requires us to write Dao layer interface, and MyBatis creates dynamic proxy object of the interface according to Dao layer interface to realize database operation. The interface implementation must comply with the following conventions.

  1. The namespace in mapper.xml must be the same as the fully qualified name of the Dao layer interface
  2. The Dao layer interface method name should be the same as the id defined in mapper.xml
  3. The input parameterType for the Dao layer interface is the same as the parameterType for each Sql in mapper.xml
  4. The output parameter type of the Dao layer interface should be the same as the resultType type of each Sql in mapper.xml

Note: if the output or input ParameterType is a List collection type, the classes of resultType and ParameterType in the mapper. XML file are the same as those in the collection generic

With that in mind, we can start writing code. Go back to IDEA and create a package DAO of the same class as the POJO package and create the interface for the UserDao. Complete the declaration of a query method in the interface.

public interface UserDao {

    List<User> getListByCondition(User user);
}
Copy the code

Write the corresponding SQL code in the usermapper. XML file as follows

<mapper namespace="com.lgy.dao.UserDao">

    <! -->
    <select id="getListByCondition" resultType="com.lgy.pojo.User" parameterType="com.lgy.pojo.User">
        select * from user where username = #{username}
    </select>

    <! -- -- -- > new
    <insert id="save" parameterType="com.lgy.pojo.User">
        insert into user values(#{id},#{username})
    </insert>

    <! Query - - - >
    <select id="getList" resultType="com.lgy.pojo.User">
        select * from user
    </select>

</mapper>
Copy the code

When this is done, we can start testing by writing the following code in the test class

    @Test
    public void testGetListByCondition(a) throws IOException {
        // Get the configuration file and convert it to the input stream
        InputStream resourceAsStream =
                Resources.getResourceAsStream("mybatis-config.xml");
        // Get SqlSessionFactory
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(resourceAsStream);
        / / get sqlSessin
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // Get the interface proxy object using the JDK dynamic proxy
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        // Build the input parameter object
        User user = new User();
        user.setUsername("jerry");
        // Execute method
        List<User> users = userDao.getListByCondition(user);
        for (User user1 : users) {
            System.out.println("id = " + user1.getId() +
                    ", username = " + user1.getUsername());
        }
        / / close the sqlSession
        sqlSession.close();
    }
Copy the code

We pre-inserted two users named Jerry into the test database user table created in the previous chapter

It worked as we expected

The mapper. XML file also leaves two methods save and getList unmodified as an exercise.

Second, core configuration

In the previous chapter, we created two configuration files, mybatis-config.xml(core configuration file) and usermapper.xml (mapping configuration file). There are actually a lot of configurations we can write in these two configuration files. Each configuration has a different function.

Detailed configuration instructions can be viewed on MyBatis Chinese official website

In this chapter, in addition to environments and mappers, which we used in the previous section. We will only cover two other common configurations in mybatis-config. XML (core configuration file), properties and typeAliases.

properties

In our actual development process, the properties attribute is also used very much in MyBatis configuration. This is because we tend to extract database-related configurations into a separate properties file. Then use the value of the resource attribute in the Properties TAB in mybatis-config.xml(core configuration file). Load the configuration in the properties file so that we can use it in mybatis-config.xml(core configuration file).

Jdbc.properties configuration code

MyBatis will parse the placeholder ${} and find the value corresponding to the Key in the placeholder to replace it

Note: The Properties tag must be written above the Environments tag otherwise an error will be reported. The demo screenshot above is for demonstration purposes only

typeAliases

TypeAliases: Set the type alias mybatis-config. XML (core configuration file) After the typeAliases tag is configured. Let me write shorter type aliases in mapper.xml instead of fully qualified names

After the typeAliases tag is configured

Note: The typeAliases tag must be written above the Environments tag. Otherwise, an error will be reported.

The typeAliases tag supports multiple configurations, but if we have a large number of POJO entities, our configuration file will become bloated. So the typeAliases tag also provides another child tag pakage. It automatically aliases all POJO entities in the specified directory. The aliases are case insensitive class names of all classes in the package.

To test the case-insensitive nature of this configuration, we deliberately change the resultType and parameterType values to UsEr. In practice, uppercase or all lowercase letters are recommended.

After making the changes, we run the test method getListByCondition.

If the command is executed successfully, the preceding configurations are correct.

In fact, MyBatis has built many types of aliases into the source code in order to simplify development. For example, java.lang.Integer can be shortened to int

View all built-in type aliases. In the org. Apache. Ibatis. Type. TypeAliasRegistry view.英 文 source code address

Third, summary

Convention over configuration makes our code more brief. In MyBatis, the Dao layer interface and mapping entities must be consistent with mapper.xml conventions to reduce the problem of hard coding. Pakage, the child of the typeAliases tag, automatically aliases all POJO classes in the specified directory and is case-insensitive to reduce the risk of bugs. Proper conventions allow us to make programming smoother without adding code control. Writing code is fundamental, and there’s a lot to think about outside of code.

If there are ambiguities or errors. Welcome to point out. Thank you.