Mybatis integrates Spring (ssm integration to be continued)-day04

Mybatis integrates Spring

  • Integrated version:
    • Spring 3.2
    • Mybaties 3.2.7
  • Precautions:
    • Spring 3.2 uses jdk1.7
    • Use jdk8 to use spring4 or above
  • Project structure:
    Insert picture description here

1. Create a project

  1. Create a javaweb project
    Insert picture description here
  2. Create a lib folder under WEB-INF to store the jar package
    Insert picture description here

2. Import the jar package

  1. Import the mybatis core package and dependent packages
    Insert picture description here
    Insert picture description here
  2. Import the mysql database driver package (import according to your own database version)
    Insert picture description here
  3. Import database dbcp connection pool
    Insert picture description here
  4. Import the spring+mvc package
    Insert picture description here
    Insert picture description here
  5. Import the Mybatis-spring integration package
    Insert picture description here
  6. Total jar package
    Insert picture description here

3. Configure the core configuration file of mybatis

<?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>
        <!--定义单个别名--><!--这样配置用到全类名的地方就可以写成别名user-->
        <!--<typeAlias type="com.it.model.User" alias="user"></typeAlias>-->

        <!--批量配置别名-->
        <!--name:指定批量定义别名的类的包名,别名为类名(首字母大小写都可以)-->
        <!--这样配置就是该包下的类名的别名就为类名,大小写都可以
        如:com.it.model包下的User类的别名就可以写为 User 或 user -->
        <package name="com.it.model"/>
    </typeAliases>

    <!--加载映射文件-->
    <mappers>
        <!--<mapper resource="com/it/sqlmap/User.xml"></mapper>-->
        <!--第一种:写映射文件名-->
        <!--<mapper resource="com/it/mapper/UserMapper.xml"></mapper>-->
        <!--第二种:使用完全限定路径【一般不用】-->
        <!--<mapper url="file:///D:\MyBatis_day01\src\com\it\mapper\UserMapper.xml"></mapper>-->
        <!--第三种:写类名(使用mapper接口的全限定名)
        一定要有个同名映射文件与之对应,如果没有,在UserMapper接口中声明注解,否则报错-->
        <!--使用注解配置时,要删除或改名映射文件,否则报错-->
        <!--注意:不使用注解时,此种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下-->
        <!--<mapper class="com.it.mapper.UserMapper"></mapper>-->
        <!--第四种:写包名【推荐使用】
        注册指定包下的所有映射文件-->
        <!--注意:此种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下-->

        <mapper resource="com/it/sqlMap/User.xml"></mapper>

        <package name="com.it.mapper"/><!--注意这种方式(包配置)只适用于Mapper代理-->
    </mappers>
</configuration>

4. Configure the data source in spring

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


    <!-- 1.配置数据库,dbcp数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///mybatis_day01"/>
        <property name="username" value="root"/>
		<property name="password" value="root"/>
        <!--最大连接数-->
        <property name="maxActive" value="10"/>
        <!--最大空闲数-->
        <property name="maxIdle" value="5"/>
    </bean>
</beans>

5. Configure SqlSessionFactory in spring

Insert picture description here

	<!--2.配置会话工厂-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
    </bean>

6. Write a User class and its mapping file

  • Provide get/set, parameterless structure, and parameterized structure for the following attributes, toString
    Insert picture description here
  • User.xml
<?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">
<!--
	namespace:命名空间,它的作用就是对SQL进行分类化管理,可以理解为SQL隔离
	注意:使用mapper代理开发时,namespace有特殊且重要的作用
 -->
<mapper namespace="user">
    <!--
        id:statement的id,要求在命名空间内唯一
        parameterType:参数的java类型
        resultType:查询出的单条结果集对应的java类型
        #{}:表示一个占位符 ?
        #{id}:表示该占位符待接收参数的名称为id。注意:如果参数为简单类型时,#{}里面的参数名称可以是任意定义
     -->
    <select id="findUserById" parameterType="int" resultType="com.it.model.User">
		SELECT * FROM USER WHERE id = #{id}
	</select>

</mapper>

7. Use the traditional way to write a UserDao and implementation class

Insert picture description here

  • Similar to the use of hibernate, SqlSessionDaoSupport is inherited here, through which you can get the getSqlSession() method to obtain the SqlSession object to operate the database
    Insert picture description here
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
    
    
    @Override
    public User findUserById(int id) {
    
    
        return this.getSqlSession().selectOne("user.findUserById",id);
    }
}

8. Configure the bean implemented by dao in spring

Insert picture description here

	<!--配置dao的几种方式-->
    <!--第一种-->
    <!--3.传统配置dao【现在一般不用】-->
    <bean class="com.it.dao.impl.UserDaoImpl" id="userDao">
        <property name="sqlSessionFactory" ref="sessionFactory"></property>
    </bean>

9. Traditional dao test

	@Test
    public void test1(){
    
    
        //1.加载spring配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //2.获取dao的bean
        UserDao userDao = (UserDao) context.getBean("userDao");

        //3.调用dao方法
        User user = userDao.findUserById(1);
        System.out.println(user);
    }

Insert picture description here

10. Change to Mapper interface to integrate dao

  1. Create UserMapper interface (just copy UserDao interface and rename it)
    Insert picture description here
  2. Create UserMapper.xml mapping file (just copy User.xml and rename it)
    Insert picture description here
<?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">
<!--
	namespace:命名空间,它的作用就是对SQL进行分类化管理,可以理解为SQL隔离
	注意:使用mapper代理开发时,namespace有特殊且重要的作用
 -->
<mapper namespace="com.it.mapper.UserMapper">

    <select id="findUserById" parameterType="int" resultType="com.it.model.User">
		SELECT * FROM USER WHERE id = #{id}
	</select>

</mapper>

11. Load the mapping file in the mybatis core configuration file

  • The code has been given above when configuring the alias
    Insert picture description here
	<!--加载映射文件-->
    <mappers>
        <!--<mapper resource="com/it/sqlmap/User.xml"></mapper>-->
        <!--第一种:写映射文件名-->
        <!--<mapper resource="com/it/mapper/UserMapper.xml"></mapper>-->
        <!--第二种:使用完全限定路径【一般不用】-->
        <!--<mapper url="file:///D:\MyBatis_day01\src\com\it\mapper\UserMapper.xml"></mapper>-->
        <!--第三种:写类名(使用mapper接口的全限定名)
        一定要有个同名映射文件与之对应,如果没有,在UserMapper接口中声明注解,否则报错-->
        <!--使用注解配置时,要删除或改名映射文件,否则报错-->
        <!--注意:不使用注解时,此种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下-->
        <!--<mapper class="com.it.mapper.UserMapper"></mapper>-->
        <!--第四种:写包名【推荐使用】
        注册指定包下的所有映射文件-->
        <!--注意:此种方法要求mapper接口和mapper映射文件要名称相同,且放到同一个目录下-->

        <mapper resource="com/it/sqlMap/User.xml"></mapper>

        <package name="com.it.mapper"/><!--注意这种方式(包配置)只适用于Mapper代理-->
    </mappers>

12. Configure MapperFactoryBean in Spring

  • Use factory bean to generate userMapper object
    Insert picture description here
	<!--第二种-->
    <!--4.由spring创建一个userMapper对象,使用工厂来创建对象-->
    <bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="userMapper">
        <property name="sqlSessionFactory" ref="sessionFactory"></property>
        <property name="mapperInterface" value="com.it.mapper.UserMapper"></property>
    </bean>

13. Use bean factory to create object test

	@Test
    public void test2(){
    
    
        //1.加载spring配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //2.获取dao的bean
        UserMapper userMapper = (UserMapper) context.getBean("userMapper");

        //3.调用dao方法
        User user = userMapper.findUserById(1);
        System.out.println(user);
    }

Insert picture description here

14. Use MapperScannerConfigurer to batch scan to create proxy objects

  • The configuration code of 12 above is troublesome, and each mapper has to create a factory bean
    Insert picture description here
	<!--第三种-->
    <!--批量创建mapper的bean对象
    内部会扫描指定包下的mapper,为每一个接口创建代理对象,名字就是类名,首字母会自动改成小写
    使用的时候直接取即可
        注意:
			1.jdk1.8 用这种方式,bean不能创建成功 ,改成jdk1.7的即可
			2.或者spring我换成spring3.2.9或以上就OK了
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.it.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
    </bean>

15. Use MapperScannerConfigurer to batch scan to create proxy object tests

-The test is the same as the previous test, just take userMapper directly (batch scanning will automatically create proxy objects)
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43414199/article/details/108921300