Spring framework -----> (5) Spring integrates MyBatis framework

One, Spring integrates MyBatis

  • concept:

Integrating MyBatis with Spring, the main problem to be solved is to hand over the SqlSessionFactory object to Spring to manage. Therefore, for this integration, you only need to register the SqlSessionFactory object generator SqlSessionFactoryBean in the Spring container, and then inject it into Dao's implementation class to complete the integration.

  • Technology used: IoC
  • Why use IoC:

Because it can create objects, integrate mybatis and spring, like a framework.

Recall the steps of using mybatis:

1) Define the dao interface, StudentDao
2) Define the mapper file StudentDao.xml
3) Define the main configuration file mybatis.xml
4) Create the dao proxy object

StudentDao dao = SqlSession.getMapper(StudentDao.class);
List<Student> students  = dao.selectStudents();

To use the dao object here, you need to use the getMapper() method.
So what conditions are needed to create the getMapper() method?
1. Create a SqlSessionFactory object
2. Obtain a SqlSession object through the openSession() method of SqlSessionFactory

Main configuration file:
1. Database information
 <environment id="mydev">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--数据库的驱动类名-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--连接数据库的url字符串-->
                <property name="url" value="jdbc:mysql://localhost:3306/springdb"/>
                <!--访问数据库的用户名-->
                <property name="username" value="root"/>
                <!--密码-->
                <property name="password" value="123456"/>
            </dataSource>
2. The location of the mapper file
   <mappers>
        <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>
        <!--<mapper resource="com/bjpowernode/dao/SchoolDao.xml" />-->
    </mappers>

Here we will use a separate connection pool to replace the default built-in mybatis, and then give the connection pool to the Spring container to create.

Through the above description, we need to let spring create the following objects:
1. Independent connection pool class object, use Ali's druid connection pool
2. SqlSessionFactory object
3. Create dao object

Here is an example to illustrate:
(1) Add the following dependencies in maven
!--单元测试-->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>

  <!--spring依赖-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.3.RELEASE</version>
  </dependency>

  <!--做spring事务依赖-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.2.3.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.3.RELEASE</version>
  </dependency>

  <!--mybatis依赖-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.1</version>
  </dependency>

  <!--mybatis-spring集成依赖-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
  </dependency>

  <!--mysql驱动-->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
  </dependency>

  <!--连接池-->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.1</version>
  </dependency>

</dependencies>

<build>
  <resources>
    <resource>
      <directory>src/main/java</directory><!--所在的目录-->
      <includes>
        <!--包括目录下的.properties,.xml 文件都会扫描到-->
        <include>**/*.properties</include>
        <include>**/*.xml</include>
      </includes>
      <filtering>false</filtering>
    </resource>
  </resources>

  <!--指定jdk版本-->
  <plugins>
    <plugin>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.1</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>
  </plugins>
</build>
(2) Create an entity class Student
public class Student {
    
    
    //属性名和列名一样
    private Integer id;
    private String name;
    private String email;
    private Integer age;
//这里省略set方法
(3) Create the StudentDao interface
public interface StudentDao {
    
    

    int insertStudent(Student student);

    List<Student> selectStudent();
}
(4) Create the mapping file StudentDao.xml
<mapper namespace="com.hcz.dao.StudentDao">
    <insert id="insertStudent">
        insert into student values (#{id},#{name},#{email},#{age})
    </insert>

    <select id="selectStudent" resultType="com.hcz.entity.Student">
        select * from student order by id desc
    </select>
</mapper>
(5) Create the main configuration file mybatis.xml
<configuration>
    <!--mybatis.xml 文件加入日志配置,可以在控制台输出执行的 sql 语句和参数-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--设置别名-->
    <typeAliases>
        <package name="com.hcz.entity"/>
    </typeAliases>

    <!--sql映射文件的位置-->
    <mappers>
        <!--告诉mybatis要执行的sql语句的位置-->
        <package name="com.hcz.dao"/>
    </mappers>
</configuration>

Note :
The data source configuration is no longer required in the main configuration file. Because the data source has to be managed by the Spring container.

(6) Create the Service interface and its implementation class
public interface StudentService {
    
    
    int addStudent(Student student);
    List<Student> queryStudent();
}
public class StudentServiceImpl implements StudentService {
    
    

    private StudentDao studentDao;

    public void setStudentDao(StudentDao studentDao) {
    
    
        this.studentDao = studentDao;
    }

    @Override
    public int addStudent(Student student) {
    
    
        int nums = studentDao.insertStudent(student);
        return nums;
    }

    @Override
    public List<Student> queryStudent() {
    
    
        List<Student> students = studentDao.selectStudent();
        return students;
    }
}
(7) Create Spring configuration file applicationContext.xml

The configuration is mainly from the following four aspects:
1) Data source
2) Register SqlSessionFactory
3) Register Mapper scanner
4) Declare custom service

1) Configure the data source (Druid Data Source DruidDataSource)
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
      init-method="init" destroy-method="close">
    <!--set注入给DruidDataSource提供连接数据库信息 -->
    <!--    使用属性配置文件中的数据,语法 ${key} -->
    <property name="url" value="${jdbc.url}" /><!--setUrl()-->
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}" />
    <property name="maxActive" value="20" />
</bean>
2) Register SqlSessionFactory
<!--注册 SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--set注入,把数据库连接池付给了dataSource属性-->
    <property name="dataSource" ref="myDataSource" />
    <!--mybatis主配置文件的位置
       configLocation属性是Resource类型,读取配置文件
       它的赋值,使用value,指定文件的路径,使用classpath:表示文件的位置
    -->
    <property name="configLocation" value="classpath:mybatis.xml" />
</bean>
3) Register the Mapper scanner
<!--注册Mapper扫描器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!--指定SqlSessionFactory对象的id-->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    <!--指定包名, 包名是dao接口所在的包名-->
    <property name="basePackage" value="com.hcz.dao"/>
</bean>

Analysis :
MapperScannerConfigurer will scan all interfaces in this package, execute the getMapper() method once for each interface, and get the dao object of each interface. The created dao object is put into the spring container. The default name of the dao object is the lowercase of the first letter of the interface name

4) Declare a custom Service implementation class
<!--声明service-->
<bean id="studentService" class="com.hcz.service.Impl.StudentServiceImpl">
    <property name="studentDao" ref="studentDao" />
</bean>

Resolution :
Since the Mapper proxy object generated by the Mapper scanner has no name, when injecting the Mapper proxy into the Service, it cannot be injected through the name, but it can be injected through the simple class name of the interface, because the object of the Dao interface is generated.

Guess you like

Origin blog.csdn.net/hcz666/article/details/113763370