[Small test] Spring integrates mybatis

First attach the project structure diagram

Insert picture description here


database table

create database `spring-learn`;
use `spring-learn`;
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(88) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 

pom.xml

 <dependencies>
    <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.5.RELEASE</version>
    </dependency>
    <!--spring事务的依赖-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>5.2.5.RELEASE</version>
      </dependency>
      <!--spring事务的依赖-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.2.5.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.9</version>
      </dependency>
      <!--数据源-->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.1.12</version>
      </dependency>

  </dependencies>
  <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <!--打包时能替换文件名,也能替换文件里面的标识符:启动时正常-->
<!--                <filtering>true</filtering>-->
                <!--打包时能替换文件名,但是不能替换文件里面的标识符,启动项目时报错。-->
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

Entity class Student.java

package com.lobster.domain;

/**
 * 实体类的属性、getter和setter方法以及toString方法
 */
public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

dao interface StudentDao.java

package com.lobster.dao;

import com.lobster.domain.Student;

import java.util.List;

public interface StudentDao {
    //增加学生
    int insertStudent(Student student);
    //查询所有的学生
    List<Student> selectStudent();
}

The mapping file StudentDao.xml of the dao interface

<?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">
<!--在命名空间将dao接口和mapper绑定-->
<mapper namespace="com.lobster.dao.StudentDao">
<!--由于我们在核心配置文件config.xml里面进行了类的别名设置,所以这里可以直接写别名也可以写类的全限定名-->
    <insert id="insertStudent" parameterType="student">
        insert  into student (name,age) values (#{name},#{age})
    </insert>
    <select id="selectStudent" resultType="com.lobster.domain.Student">
        select * from student
    </select>
</mapper>

service interface StudentService

package com.lobster.service;

import com.lobster.domain.Student;

import java.util.List;

public interface StudentService {
    //添加学生的service
    int addStudent(Student student);
    //查询所有学生的service
    List<Student> queryStudent();
}

The implementation class of the service interface StudentServiceImpl

package com.lobster.service.impl;

import com.lobster.dao.StudentDao;
import com.lobster.domain.Student;
import com.lobster.service.StudentService;

import java.util.List;

public class StudentServiceImpl implements StudentService {
    //引入dao层
    private StudentDao studentDao;
    //对应的setter方法
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

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

    @Override
    public List<Student> queryStudent() {
        List<Student> students = studentDao.selectStudent();
        return students;
    }
}

mybatis-config.xml

<?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">

<!-- MyBatis的全局配置文件 -->
<configuration>
    <!--设置实体类的别名-->
    <typeAliases>
        <package name="com.lobster.domain"/>
    </typeAliases>

    <!-- 2.加载Mapper配置文件,路径以斜杠间隔: xx/xx/../xx.xml -->
    <mappers>
        <!--以是这种格式-->
<!--        <mapper resource="xx/xx/DoorMapper.xml"/>-->
    <!--也可以是这种格式-->
        <package name="com.lobster.dao"/>
    </mappers>
</configuration>

jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/spring-learn
jdbc.username=root
jdbc.password=123456

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--把外部配置文件引进来-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--声明数据源Druid-->
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!--        <property name="url" value="jdbc:mysql://localhost:3306/spring-learn"/>-->
<!--        <property name="username" value="root"/>-->
<!--        <property name="password" value="123456"/>-->
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!-- 声明SqlSessionFactoryBean-->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--指定数据源,在这里将它与我们在上面声明的数据源匹配起来-->
        <property name="dataSource" ref="myDataSource"/>
        <!--指定mybatis核心配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <!--
        声明MapperScannerConfiguration
        作用:循环basePackage所表示的包,把包中的每个接口都能找到,
             调用sqlSession的getMapper把每个dao接口创建出dao对象
             dao对象放在容器中
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定sqlSessionFactory对象,在这里将它与上面声明的SqlSessionFactoryBean匹配起来-->
        <property name="sqlSessionFactoryBeanName" value="factory"/>
        <!--指定基本包,dao接口所在的包-->
        <property name="basePackage" value="com.lobster.dao"/>
    </bean>
    <!--声明service-->
    <bean id="studentService" class="com.lobster.service.impl.StudentServiceImpl">
        <!--将刚刚通过mapper创建的dao对象交给service-->
        <property name="studentDao" ref="studentDao"/>
    </bean>
</beans>