Mybatis integrated spring detailed course (suitable for beginners)

Keywords: Java Mybatis Spring xml JDBC

Catalog

@
Mybatis integration of spring is actually the integration of SM in SSM framework.

1. Integration ideas

The idea of integration is actually the core of Mybatis to integrate spring

1. SqlSessionFactory objects should be placed in the spring container as a single instance. Spring is a single instance by default.
2. In the traditional development mode of dao, sqlsession object should be obtained from spring container.
3. In the mapper proxy form, the mapper proxy object should be obtained directly from the spring container.
4. The connection of the database and the transaction management of the database connection pool are all completed by the spring container.

2. Integrate the required jar package

1. jar package of spring
2. Mybatis jar package
3. Integration package of Spring+mybatis.
4. Mysql database driver jar package.
5. jar package of database connection pool.

jar package, I hope you all have it, or I will be embarrassed by QAQ

3. Steps of integration

3.1. Create project

Create a java project as follows:

3.2. Import jar package

The jar package mentioned above needs to be imported, as shown below:

3.3. Add configuration file

1. Configuration file of mybatisspring
2. Configuration file sqlmapConfig.xml
a) database connection and connection pool
b) transaction management (it can not be configured temporarily)
c)sqlsessionFactory object, configured in spring container
D) maper proxy objects or dao implementation classes are configured into spring containers.

Create a config copy of the resource folder to join the configuration file, as shown in the following figure

3.3.1. Configure SqlMapConfig.xml

The configuration file is SqlMapConfig.xml, as follows:

<?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>
    <!-- Setting aliases -->
    <typeAliases>
        <!-- 2. If you specify a scan package, all classes in the package will be aliased. The alias name is the class name, which is not case sensitive -->
        <package name="com.gx.mybatis.pojo" />
    </typeAliases>

</configuration>
3.3.2.applicationContext.xml

SqlSessionFactoryBean belongs to mybatis spring
For spring, mybatis is another architecture that needs to integrate jar packages.

Add the source code of mybatis-spring-1.2.2.jar to the project, as shown below

Effect, as shown in the figure below, the icon changes, indicating that the source code is loaded successfully:

To integrate Mybatis, SqlSessionFactoryBean is required, as shown in the following figure:

applicationContext.xml, the configuration content is as follows

Due to the original Dao development, so

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

   <!-- Load profile -->
   <context:property-placeholder location="classpath:db.properties" />

    <!-- Database connection pool -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- To configure SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- To configure mybatis Core profile -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
        <!-- Configure data sources -->
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>
3.3.3. Configure db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
3.3.4. Configure log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
3.3.5. Effect:

The final effect of the added configuration file is as follows:

So far, the environment is OK!!!!

4. Two implementation methods of Dao development

1. Development mode of Original dao
2. Mapper agent development mode
a) directly configure Mapper agent
b) use scan package to configure Mapper agent

Demand:
1. Query according to user id
2. Fuzzy query based on user name
3. Add user

4.1. Create pojo

public class User {
    private int id;
    private String username;// User name
    private String sex;// Gender
    private Date birthday;// Birthday
    private String address;// address

get/set. . . 
}

4.2. Development mode of traditional dao (mode 1)

The original DAO development interface + implementation class.
Need dao implementation class need to inherit SqlsessionDaoSupport class

4.2.1. Implement Mapper.xml

Write the User.xml configuration file as follows:

<?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="test">
    <!-- According to users id query -->
    <select id="queryUserById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    </select>

    <!-- Fuzzy query user based on user name -->
    <select id="queryUserByUsername" parameterType="string"
        resultType="user">
        select * from user where username like '%${value}%'
    </select>

    <!-- Add user -->
    <insert id="saveUser" parameterType="user">
        <selectKey keyProperty="id" keyColumn="id" order="AFTER"
            resultType="int">
            select last_insert_id()
        </selectKey>
        insert into user
        (username,birthday,sex,address)
        values
        (#{username},#{birthday},#{sex},#{address})
    </insert>

</mapper>
4.2.2. Load Mapper.xml

Configure SqlMapConfig as follows:

4.2.3. Implementation of UserDao interface
public interface UserDao {
    /**
     * Query users by id
     * 
     * @param id
     * @return
     */
    User queryUserById(int id);

    /**
     * Fuzzy query user list based on user name
     * 
     * @param username
     * @return
     */
    List<User> queryUserByUsername(String username);

    /**
     * Preservation
     * 
     * @param user
     */
    void saveUser(User user);

}
4.2.4. Write UserDaoImpl implementation interface and inherit SqlSessionDaoSupport

Write DAO implementation class, which must inherit SqlSessionDaoSupport
SqlSessionDaoSupport provides getSqlSession() method to get SqlSession

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
    @Override
    public User queryUserById(int id) {
        // Get SqlSession
        SqlSession sqlSession = super.getSqlSession();

        // Using SqlSession to perform operations
        User user = sqlSession.selectOne("queryUserById", id);

        // Do not close sqlSession

        return user;
    }

    @Override
    public List<User> queryUserByUsername(String username) {
        // Get SqlSession
        SqlSession sqlSession = super.getSqlSession();

        // Using SqlSession to perform operations
        List<User> list = sqlSession.selectList("queryUserByUsername", username);

        // Do not close sqlSession

        return list;
    }

    @Override
    public void saveUser(User user) {
        // Get SqlSession
        SqlSession sqlSession = super.getSqlSession();

        // Using SqlSession to perform operations
        sqlSession.insert("saveUser", user);

        // No commit, transactions are managed by spring
        // Do not close sqlSession
    }
}
4.2.4.1.SqlSessionDaoSupport source code

The implementation class must inherit SqlSessionDaoSupportSqlSessionDaoSupport and provide getSqlSession() method to get SqlSession

4.2.5. Configure dao

Configuring dao implementation classes into spring containers

<!-- Dao Original Dao -->
    <bean id="userDao" class="com.gx.mybatis.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
    </bean>
4.2.6. Create test

Create test methods, and you can directly create test Junit cases.
Create as shown in the figure below.


Write the test method as follows:

public class UserDaoTest {
    private ApplicationContext context;

    @Before
    public void setUp() throws Exception {
        this.context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }

    @Test
    public void testQueryUserById() {
        // Get userDao
        UserDao userDao = this.context.getBean(UserDao.class);

        User user = userDao.queryUserById(1);
        System.out.println(user);
    }

    @Test
    public void testQueryUserByUsername() {
        // Get userDao
        UserDao userDao = this.context.getBean(UserDao.class);

        List<User> list = userDao.queryUserByUsername("Zhang");
        for (User user : list) {
            System.out.println(user);
        }
    }

    @Test
    public void testSaveUser() {
        // Get userDao
        UserDao userDao = this.context.getBean(UserDao.class);

        User user = new User();
        user.setUsername("Xia Hou Tang pit");
        user.setSex("1");
        user.setBirthday(new Date());
        user.setAddress("Three countries");
        userDao.saveUser(user);
        System.out.println(user);
    }
}

5.Mapper agent development dao (mode 2)

5.1. Implement Mapper.xml

Write the UserMapper.xml configuration file as follows:

<?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="cn.itcast.mybatis.mapper.UserMapper">
    <!-- According to users id query -->
    <select id="queryUserById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    </select>

    <!-- Fuzzy query user based on user name -->
    <select id="queryUserByUsername" parameterType="string"
        resultType="user">
        select * from user where username like '%${value}%'
    </select>

    <!-- Add user -->
    <insert id="saveUser" parameterType="user">
        <selectKey keyProperty="id" keyColumn="id" order="AFTER"
            resultType="int">
            select last_insert_id()
        </selectKey>
        insert into user
        (username,birthday,sex,address) values
        (#{username},#{birthday},#{sex},#{address})
    </insert>
</mapper>
5.2. Implement the UserMapper interface
public interface UserMapper {
    /**
     * Query by user id
     * 
     * @param id
     * @return
     */
    User queryUserById(int id);

    /**
     * Fuzzy query user based on user name
     * 
     * @param username
     * @return
     */
    List<User> queryUserByUsername(String username);

    /**
     * Add user
     * 
     * @param user
     */
    void saveUser(User user);
}
5.3. Mode 1: configure mapper agent

Add configuration in applicationContext.xml
MapperFactoryBean also belongs to mybatis spring integration package

<!-- Mapper Agent development mode 1, configuration Mapper Surrogate object -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <!-- To configure Mapper Interface -->
    <property name="mapperInterface" value="com.gx.mybatis.mapper.UserMapper" />
    <!-- To configure sqlSessionFactory -->
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
5.4. Create test
public class UserMapperTest {
    private ApplicationContext context;

    @Before
    public void setUp() throws Exception {
        this.context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }

    @Test
    public void testQueryUserById() {
        // Get Mapper
        UserMapper userMapper = this.context.getBean(UserMapper.class);

        User user = userMapper.queryUserById(1);
        System.out.println(user);
    }

    @Test
    public void testQueryUserByUsername() {
        // Get Mapper
        UserMapper userMapper = this.context.getBean(UserMapper.class);

        List<User> list = userMapper.queryUserByUsername("Zhang");

        for (User user : list) {
            System.out.println(user);
        }
    }
    @Test
    public void testSaveUser() {
        // Get Mapper
        UserMapper userMapper = this.context.getBean(UserMapper.class);

        User user = new User();
        user.setUsername("Angela");
        user.setSex("1");
        user.setBirthday(new Date());
        user.setAddress("China");

        userMapper.saveUser(user);
        System.out.println(user);
    }
}
5.5. Mode 2: configure mapper in the form of scanning package (commonly used in development)
<! -- mapper agent mode development mode 2, scan package mode configuration agent -- >
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <! -- configure Mapper interface -- >
    <property name="basePackage" value="com.gx.mybatis.mapper" />
</bean>

The id of each mapper proxy object is the class name, with lowercase initial

6. Summary of Dao's development

If this article helps you a little bit, please give me a compliment. Thank you~

In the end, if there are any deficiencies or irregularities, please correct and criticize. Thank you very much! If you have any questions, please leave a message and reply as soon as possible!

You are welcome to pay attention to my public address, explore technology, yearn for technology and pursue technology.

Posted by shakuni on Thu, 12 Dec 2019 04:40:54 -0800