Spring集成MyBatis


title: Spring集成MyBatis
tag: JAVA


把Spring框架和MyBatisi框架集成在一起,像一个框架一样使用,非常非常简单方便!

步骤

1.新建maven项目

2.加入maven依赖

1.spring依赖
2.mybatis依赖
3.mysql驱动
4.spring的事务的依赖
5.mybatis和spring集成的依赖,(mybatis官方提供的,用来在spring项目中创建SqlSessionFactory,dao对象的)
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>xyz.guawaz</groupId>
  <artifactId>ch09-spring-mybatis</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>ch09-spring-mybatis</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.guawaz.xyz</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--spring 核心ioc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.3.9</version>
    </dependency>
    <!--spring事务-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.3.9</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.3.9</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>2.0.6</version>
    </dependency>
    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.25</version>
    </dependency>
    <!--数据库连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.6</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>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.1</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target> </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

3.创建实体类

package xyz.guawaz.domain;

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

    public Student() {
    }

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

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

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

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

4.创建dao接口和mapper文件

package xyz.guawaz.dao;

import xyz.guawaz.domain.Student;

import java.util.List;

public interface StudentDao {

    int insertStudent(Student student);

    List<Student> selectStudents();
}

<?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="xyz.guawaz.dao.StudentDao">
    
    <insert id="insertStudent">
        insert into student values(#{id},#{name},#{email},#{age})
    </insert>

    <select id="selectStudents" resultType="xyz.guawaz.domain.Student">
       select id,name,email,age from student order by id desc
    </select>

</mapper>

5.创建mybatis主配置文件

mybatis的主配置文件,定义了数据库的配置信息和sql映射文件的位置

<?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>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--设置别名-->
    <typeAliases>
        <!--实体类所在的包名-->
        <package name="xyz.guawaz.domain"/>
    </typeAliases>

    <mappers>
        <!--name是包名,这个包中的所有mapper文件可以一次性加载-->
        <package name="xyz.guawaz.dao"/>
    </mappers>
</configuration>

6.创建Service接口和实现类,属性是dao

接口声明两个方法
package xyz.guawaz.service;

import xyz.guawaz.domain.Student;

import java.util.List;


public interface StudentService {
    int addStudent(Student student);
    List<Student> queryStudents();
}

实现类实现这两个方法,dao是属性

package xyz.guawaz.service.impl;

import xyz.guawaz.dao.StudentDao;
import xyz.guawaz.domain.Student;
import xyz.guawaz.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 List<Student> queryStudents() {
        List<Student> students = studentDao.selectStudents();
        return students;
    }
}

7.创建Spring配置文件applicationContext

1.数据源

之前单独用mybatis是在mybatis.xml中配置数据源,用的是mybatis自己提供的数据库连接池,现在不用mybatis的连接池了,在spring配置文件中配置druid数据库连接池为数据源

    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--声明数据源DataSource -->
    <bean id="dataSource" 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.password}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
    </bean>
2.SqlSessionFactory

之前说过了,SqlSessionFactory接口:默认实现类是DefaultSqlSessionFactory。它是一个重量级对象,程序创建一个对象耗时较长,使用资源较多,整个项目中只需创建一个,它的功能是负责创建SqlSession对象。使用openSession()方法来获取SqlSession对象

    <!--声明mybatis中提供的SqlSessionFactoryBean类,这个类内部是提供SqlSessionFactory的-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--set注入,把数据库连接池赋给了dataSource属性-->
        <property name="dataSource" ref="dataSource"/>
        <!--mybatis主配置文件的位置-->
        <!--configLocation属性是Resoource类型,读取配置文件,
            它的赋值使用value,指定文件的路径,使用classpath:表示文件的位置
        -->
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>
3.Dao对象

之前也说过了,我们可以通过mybatis提供的动态代理机制创建dao对象,使用的是:SqlSession.getMapper(dao接口),由于现在要和spring集成起来,那么dao对象理应交给spring容器来管理,mybatis官方提供了一个类:MapperScannerConfigurer,这个类在内部调用getMapper()生成每个dao接口的代理对象,这个类需要的参数有两个,哪两个?显而易见啊

    <!--创建dao对象,使用SqlSession的getMapper(Student.class)-->
    <!--MapperScannerConfigurer这个类在内部调用getMapper()生成每个dao接口的代理对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定sqlSessionFactory对象的id-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--指定dao接口所在的包名
            MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行一次getMapper()方法
            得到每个接口的dao对象
            创建好的dao对象放入spring容器中 dao对象默认名称是接口名首字母小写
        -->
        <property name="basePackage" value="xyz.guawaz.dao"/>
    </bean>

4.声明自定义的service
    <bean id="studentService" class="xyz.guawaz.service.impl.StudentServiceImpl">
        <property name="studentDao" ref="studentDao"/>
    </bean>

8.创建测试类,获取Service对象,通过Service调用dao完成数据库的访问

package xyz.guawaz;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xyz.guawaz.dao.StudentDao;
import xyz.guawaz.domain.Student;
import xyz.guawaz.service.StudentService;

import java.util.List;

public class MyTest {
    /*打印看一下容器中都用哪些对象*/
    @Test
    public void test01(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        String names[] = ac.getBeanDefinitionNames();
        for (String na:names){
            System.out.println("容器中对象名称:" + na);
        }
    }

    /*从容器中获取dao对象(其实是spring帮我们创建的dao代理对象)*/
    @Test
    public void testDaoInsert(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//      获取容器中的dao对象
        StudentDao studentDao = (StudentDao) ac.getBean("studentDao");

        Student student = new Student();
        student.setName("huyang");
        student.setEmail("huyang@qq.com");
        student.setAge(0);
        student.setId(1010);

        studentDao.insertStudent(student);


    }

    /*从容器中获取service对象,执行service中的方法*/
    @Test
    public void testStudentService(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//      获取容器中的service对象
        StudentService service = (StudentService) ac.getBean("studentService");

        Student student = new Student();
        student.setName("yangyang");
        student.setEmail("yangyang@qq.com");
        student.setAge(19);
        student.setId(1009);

        service.addStudent(student);
//        spring和mybatis整合使用时 是自动提交事务的 无需执行sqlSession.commit()
    }

    @Test
    public void testStudentService1(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//      获取容器中的service对象
        StudentService service = (StudentService) ac.getBean("studentService");


        List<Student> students = service.queryStudents();
        students.forEach(stu-> System.out.println(stu));
//        spring和mybatis整合使用时 是自动提交事务的 无需执行sqlSession.commit()
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值