Spring04-- Spring 集成 MyBatis

Spring04-- Spring 集成 MyBatis

  • 1.1 建立数据库表
  • 1.2 Maven依赖
  • 1.3 定义实体类Student
  • 1.4 定义StudentDao接口
  • 1.5 定义映射文件mapper
  • 1.6 定义 Service 接口和实现类
  • 1.7 定义 MyBatis 主配置文件
  • 1.8 创建Spring配置文件
    • 1) 数据源的配置
    • 2)从属性文件获取数据库连接信息
    • 3)注册SqlSessionFactoryBean
    • 4)定义mapper文件扫描器
    • 5)向 Service 注入接口名
    • 6)Spring配置文件全部配置
  • 1.9 测试方法
    • 1)insertStudent()
    • 2)updateStudent()
    • 3)deleteStudent()
    • 4)selectStudentById()
    • 5)selectStudents()

1.1 建立数据库表

Spring04-- Spring 集成 MyBatis_第1张图片

1.2 Maven依赖

  <dependencies>
    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.5.1version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.1version>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>8.0.27version>
    dependency>
    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.1.12version>
    dependency>
  dependencies>

  <build>
    
    <resources>
      <resource>
        <directory>src/main/javadirectory>
        <includes>
          <include>**/*.propertiesinclude>
          <include>**/*.xmlinclude>
        includes>
        <filtering>falsefiltering>
      resource>

      <resource>
        <directory>src/main/resourcesdirectory>
        <includes>
          <include>**/*.propertiesinclude>
          <include>**/*.xmlinclude>
        includes>
        <filtering>falsefiltering>
      resource>
    resources>
    
    
    <plugins>
      <plugin>
        <artifactId>maven-compiler-pluginartifactId>
        <version>3.1version>
        <configuration>
          <source>1.8source>
          <target>1.8target>
        configuration>
      plugin>
    plugins>
  build>

1.3 定义实体类Student

package com.suyv.spring.domain;

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student() {
        
    }

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = 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 +
                '}';
    }
}

1.4 定义StudentDao接口

package com.suyv.spring.dao;

import com.suyv.spring.domain.Student;

import java.util.List;

public interface StudentDao {
    int insertStudent(Student student);
    int updataStudent(Student student);
    int deleteStudent(int id);

    Student selectStudentById(int id);
    List<Student> selectStudents();
}

1.5 定义映射文件mapper


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.suyv.spring.dao.StudentDao">

    <insert id="insertStudent">
        insert into stu(name,age) values(#{name},#{age})
    insert>

    <update id="updataStudent">
        update stu set name=#{name} ,age=#{age} where id=#{id}
    update>

    <delete id="deleteStudent">
        delete from stu where id=#{id}
    delete>

    <select id="selectStudentById" resultType="com.suyv.spring.domain.Student">
        select * from stu where id=#{id}
    select>

    <select id="selectStudents" resultType="com.suyv.spring.domain.Student">
        select * from stu order by id desc
    select>

mapper>

1.6 定义 Service 接口和实现类

service接口:

package com.suyv.spring.service;

import com.suyv.spring.domain.Student;

import java.util.List;

public interface StudentService {

    int addStudent(Student student);

    int modifyStudent(Student student);

    int removeStudent(Student student);

    Student findStudentById(int id);

    List<Student> queryStudents();
}

实现类:

package com.suyv.spring.service.impl;

import com.suyv.spring.dao.StudentDao;
import com.suyv.spring.domain.Student;
import com.suyv.spring.service.StudentService;

import java.util.List;

public class StudentServiceImpl implements StudentService {

    //引用类型
    private StudentDao studentDao;

    //使用set注入,赋值
    public void setStudentDao(StudentDao studentDao){
        this.studentDao = studentDao;
    }

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

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

    @Override
    public int removeStudent(int id) {
        int num = studentDao.deleteStudent(id);
        return num;
    }

    @Override
    public Student findStudentById(int id) {
        Student student = studentDao.selectStudentById(id);
        return student;
    }

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

1.7 定义 MyBatis 主配置文件

在 src 下定义 MyBatis 的主配置文件,命名为 mybatis.xml。
这里有两点需要注意:
1.主配置文件中不再需要数据源的配置了。因为数据源要交给 Spring 容器来管理了。
2.这里对 mapper 映射文件的注册,使用标签,即只需给出mapper 映射文件所在的包即可。因为 mapper 的名称与 Dao 接口名相同,可以使用这种简单注册方式。这种方式的好处是,若有多个映射文件,这里的配置也是不用改变的。当然,也可使用原来的标签方式。


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    
    <settings>
        
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    
    
    <typeAliases>
        
        <package name="com.suyv.spring.domain"/>
    typeAliases>

    
    <mappers>
        
        <package name="com.suyv.spring.dao"/>
    mappers>
configuration>

1.8 创建Spring配置文件

1) 数据源的配置

使用 JDBC 模板,首先需要配置好数据源,数据源直接以 Bean 的形式配置在 Spring 配置文件中。根据数据源的不同,其配置方式不同:
Druid 数据源 DruidDataSource
Druid 是阿里的开源数据库连接池。是 Java 语言中最好的数据库连接池。Druid 能够提供强大的监控和扩展功能。Druid 与其他数据库连接池的最大区别是提供数据库的
官网:https://github.com/alibaba/druid
使用地址:https://github.com/alibaba/druid/wiki/常见问题
配置连接池:
Spring04-- Spring 集成 MyBatis_第2张图片
Spring 配置文件:
Spring04-- Spring 集成 MyBatis_第3张图片

2)从属性文件获取数据库连接信息

在这里插入图片描述
该属性文件若要被 Spring 配置文件读取,其必须在配置文件中进行注册。使用标签。
方式
该方式要求在 Spring 配置文件头部加入 spring-context.xsd 约束文件标签中有一个属性 location,用于指定属性文件的位置。
在这里插入图片描述

3)注册SqlSessionFactoryBean

Spring04-- Spring 集成 MyBatis_第4张图片

4)定义mapper文件扫描器

Mapper 扫描配置器 MapperScannerConfigurer 会自动生成指定的基本包中 mapper 的代理对象。该 Bean 无需设置 id 属性。basePackage 使用分号或逗号设置多个包。
Spring04-- Spring 集成 MyBatis_第5张图片

5)向 Service 注入接口名

在这里插入图片描述

6)Spring配置文件全部配置


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

    
    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.passwd}" />
        <property name="maxActive" value="${jdbc.max}" />
    bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="configLocation" value="classpath:mybatis.xml" />
    bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <property name="basePackage" value="com.suyv.spring.dao"/>
    bean>

    <bean id="studentService" class="com.suyv.spring.service.impl.StudentServiceImpl">
        <property name="studentDao" ref="studentDao" />
    bean>
beans>

1.9 测试方法

1)insertStudent()

测试方法:

    @Test
    public void testServiceInsert(){
        String config="applicationContext.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        //获取spring容器中的service方法
        StudentService service = (StudentService) ctx.getBean("studentService");
        Student student  = new Student();
        student.setName("李刚");
        student.setAge(28);
        int nums = service.addStudent(student);
        System.out.println("nums="+nums);
    }

运行结果:
Spring04-- Spring 集成 MyBatis_第6张图片
Spring04-- Spring 集成 MyBatis_第7张图片

2)updateStudent()

测试方法:

    @Test
    public void testUpdataStudent(){
        String config="applicationContext.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        //获取spring容器中的service方法
        StudentService service = (StudentService) ctx.getBean("studentService");
        Student student  = new Student();
        student.setId(4);
        student.setName("李明");
        student.setAge(30);
        int nums = service.modifyStudent(student);
        System.out.println("nums="+nums);
    }

运行结果:
Spring04-- Spring 集成 MyBatis_第8张图片
Spring04-- Spring 集成 MyBatis_第9张图片

3)deleteStudent()

测试方法:

    @Test
    public void testDeleteStudent(){
        String config="applicationContext.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        //获取spring容器中的service方法
        StudentService service = (StudentService) ctx.getBean("studentService");
        int id = 4;
        int nums = service.removeStudent(id);
        System.out.println("nums="+nums);
    }

运行结果:
Spring04-- Spring 集成 MyBatis_第10张图片
Spring04-- Spring 集成 MyBatis_第11张图片

4)selectStudentById()

测试方法:

    @Test
    public void testSelectStudentById() {
        String config = "applicationContext.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        StudentService service = (StudentService) ctx.getBean("studentService");
        int id = 1;
        Student student = service.findStudentById(id);
        System.out.println(student);
    }

运行结果:
Spring04-- Spring 集成 MyBatis_第12张图片

5)selectStudents()

测试方法:

    @Test
    public void testServiceSelect() {
        String config = "applicationContext.xml";
        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        StudentService service = (StudentService) ctx.getBean("studentService");
        List<Student> students = service.queryStudents();
        for (Student stu : students) {
            System.out.println(stu);
        }
    }

运行结果:
Spring04-- Spring 集成 MyBatis_第13张图片

你可能感兴趣的:(SSM复习,spring,java,mybatis,ssm)