MyBatis configuration in Spring

When we need to use the database to write the project in Spring, now we generally use the framework of MyBatis to help us write the code, but after learning SSM, we need to know that M refers to MyBatis. Here, in Spring, how to configure the MyBatis environment summary.

Prepare the environment

The first thing we need to prepare is the relevant Jar package:

Mybatis

Spring core Jar package and integrate MyBatis Jar package:

Among themMybatis - spring - 1.2.1 jarBags need to go to the official websitedownload.

Configure the environment

Import all the Jar packages into lib and add them to the project environment. Project Structure:

application

Once you’ve structured your project, you can start writing code for a test project that simulates user login with the simplest console possible (MVC design pattern). Realize object understanding decoupling and logic decoupling. UserService interface:

public interface UserService {
    // User login
    User userLoginService(String username,String pwd) throws IOException;
}
Copy the code

UserServiceImpl Interface implementation class:

public class UserServiceImpl implements UserService {
    private UserMapper userMapper;

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User userLoginService(String username, String pwd){
        if(userMapper! =null) {return userMapper.userLoginMapper(username,pwd);
        }
        return null; }}Copy the code

UserMapper interface (mapping file not written with annotations) :

public interface UserMapper {
    @Select("select * from t_user where userName=#{uname} and password=#{pwd}")
    User userLoginMapper(@Param("uname") String username,@Param("pwd") String pwd);
}
Copy the code

User entity class:

public class User {
    private String userid;
    private String userName;
    private String password;
    private Double money;
}
Copy the code

The Spring configuration file applicationContext.xml


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <! DriverManagerDataSource DriverManagerDataSource -->
    <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    </bean>

    <! Mybatis = 1.3.1.jar = mybatis = 1.3.1.jar = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory = SqlSessionFactory
    <bean name="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <! Get interface bean from UserMapper -->
    <bean name="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <! -- Scan Mapper path -->
        <! Spring will return the mapper scan results (mapper layer objects) and store them in the Spring container as the first letter of the interface name.
        <property name="basePackage" value="com.lyl.mapper"/>
        <property name="sqlSessionFactory" ref="factory"/>
    </bean>

    <! -- Configure UserServiceImpl bean -->
    <bean name="us" class="com.lyl.service.impl.UserServiceImpl">
        <! -- Dependency injection -->
        <property name="userMapper" ref="userMapper"/>
    </bean>

</beans>
Copy the code

Test Test class:

public class Test {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter user name:");
        String user = scanner.next();
        System.out.println("Please enter your password:");
        String pwd = scanner.next();
        ApplicationContext context  = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService us = (UserService) context.getBean("us"); User user1 = us.userLoginService(user, pwd); System.out.println(user1); }}Copy the code

Query result:


There are two main points to look at: the Spring configuration file and the userLoginService implementation of the UserServiceImpl code.

Looking at the Spring configuration file, there are roughly four pieces

  1. Configuring the data source Bean
  2. Configure the beans for SqlSessionFactory
  3. Gets the bean of the UserMapper interface
  4. Configure the bean for UserServiceImpl (with Setter injection for logical decoupling)

1. Very simple, is to prepare the database connection required parameters (after the may be a bit miscellaneous, not interested can skip!) DriverManagerDataSource = DriverManagerDataSource = DriverManagerDataSource = DriverManagerDataSource = DriverManagerDataSource; A DataSource uses a Connection object to perform operations on the database. But why is the DataSource class key? In fact, we in a single MyBatis configuration file also need to carry out the relevant configuration of database connection parameters, and the core is not the relevant configuration of database connection parameters, to put it simply, several parameters, so where will the parameters be saved? SqlSessionFactory: SqlSessionFactory: SqlSessionFactory

    InputStream is = Resources.getResourceAsStream("mybatis.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession();
Copy the code

SqlSessionFactory finally calls the build() method of SqlSessionFactoryBuilder(). Click here to see that this overloaded method is called

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
        SqlSessionFactory var5;
        try {
            XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
            var5 = this.build(parser.parse());
        } catch (Exception var14) {
            throw ExceptionFactory.wrapException("Error building SqlSession.", var14);
        } finally {
            ErrorContext.instance().reset();

            try {
                inputStream.close();
            } catch (IOException var13) {
            }

        }
        return var5;
    }
Copy the code

XMLConfigBuilder class XMLConfigBuilder class XMLConfigBuilder

This class parses the Configuration file of Mybatis and stores the parsed information of Myabtis in the Configuration object. The Configuration object runs through the entire execution process of MyBatis and provides various required Configuration information for the execution process of MyBatis.

This class is used to parse our mybatis. XML configuration file. The parse() method is used to parse tags and store content

public SqlSessionFactory build(Configuration config) {
        return new DefaultSqlSessionFactory(config);
    }
Copy the code

This method returns the DefaultSqlSessionFactory object, which is not important, because if we click on it, we will not understand it. View information:

Configuration is like the general manager of Mybatis, where all the Configuration information of Mybatis is stored, in addition, it provides the method of setting the Configuration information. Configuration can obtain property values from the Configuration file.

This Configuration is the object that stores the parsed parameters of the MyBatis Configuration file. Get in there and look at the code. You’ll get dizzy. Don’t worry! Mybatis. XML is a database connection configuration file that contains the connection details of the database.

  • Id: Id of the current environment variable, such as dev, prod, and so on
  • TransactionFactory: Transaction manager in the current environment
  • DataSource: dataSource in the current environment

Finally found in MyBatisDataSourceData source, through layer upon layer looking at the source code, sorting out the logical relationship, we found that to get SqlSessionFactory finally we need to get the database Connection parameters, after all, we only need to get Connection, and MyBatisDataSourceIs to save the connection parameters, as to how to achieve, we all give the framework, focus on the business code can. Have you found that in essence, what we care about in MyBatis or Spring configuration file is configuration parameters, so there is no need to tangle with the relationship of all the source code at the bottom, grasp the essence, the essence is that two different frameworks need the same parameter information, we can do a good job of parameter configuration. Feel messy can also skip, go to look up other materials (after all, it is also written when learning).2.SqlSessionFactory is the core Java class of MyBatis database operation, we must get SqlSession from it to carry out specific SQL operations, so in Spring with Setter to achieve data source Bean injection, usingmybatis-spring.jarMybatis package, which is integrated by Spring. This step is to get the SqlSessionFactory bean3.Get the interface bean of UserMapper,basePackageThis property specifies the Mapper mapping file to scanPackage path.sqlSessionFactoryInject the SqlSessionFactory bean above. Let’s print the names of all the beans in the Spring container at this point:It turns out that we only configured four beans and there are five Bean objects, one too manyuserMapperIt turns out that the name of our Mapper interface is like a lowercase letter, and there must be some connection. In fact, Spring will automatically instantiate the scanned Mapper interface into beans and store them in the Spring container when scanning the mapping file under the Mapper package path. This way we don’t have to manually reconfigure the bean when we call the Mapper interface bean.4.This step is simple Setter dependency injection.

If DI is not used, then we usually need to use an interface or class method. We need to create an instance of the interface or class to call the method, so there is no decoupling of the code. If you use DI, we don’t need to take the initiative to create the called party, only need to set the bean in the Spring container, business in the code we just get the final bean, realize decoupling of the code, the relationship between A and B is no longer directly, but through the Spring container, but the code is run, is still A step by step, but realize decoupling, Easy maintenance.

summary

The above is a summary of the simple case of learning Spring integration of MyBatis, which will also have many problems and deficiencies. To more practical and source summary.

Error: ContextLoaderListener is used in a Web project.

<context-param>
    <! ContextConfigLocation --> contextConfigLocation --> contextConfigLocation
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
Copy the code

The variable name in the param-name tag must be contextConfigLocation! Must say contextConfigLocation! Must say contextConfigLocation! .