Spring&Mybatis整合及Spring中JDBCTemplate的使用

2023-05-16

Spring和Mybatis整合

在mybatis中,操作数据库需要获取到SQLSession对象,而该对象的实例过程在mybatis是通过SQLSessionFactoryBuilder读取全局配置文件来实例化一个SQLSessionFactory,通过SQLSessionFactory来获取到SQLSession对象,而和spring整合过程中,可以通过单例的形式来管理SQLSessionFactory对象,mybatis-spring中提供了一个SQLSessionFactoryBean类来实例化SQLSessionFactory,SQLSessionFactory中需要必须的属性是DataSource与Mappers。

整合步骤如下

1、引入mybatis-spring

为了完成spring和mybatis的整合,由mybatis提供了一个整合jar包:mybatis-spring

        <!--mybatis和spring整合依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

完整的依赖文件如下:

<?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>org.example</groupId>
  <artifactId>springTest</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>springTest</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

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

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.7.4</version>
    </dependency>

    <dependency>
      <groupId>aopalliance</groupId>
      <artifactId>aopalliance</artifactId>
      <version>1.0</version>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.12</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>

    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

2.开发过程

mybatis全局配置文件(可以忽略)、Pojo类、Mapper.java接口文件和Mapper.xml配置文件

StudentMapper.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">
<mapper namespace="org.example.dao.StudentMapper">
    <select id="selectStudentById" parameterType="int" resultType="org.example.bean.Student1">
        select * from Student where SID = #{SID}
    </select>
</mapper>

 Student1

package org.example.bean;

/**
 * Description :
 * Created by Resumebb
 * Date :2021/3/26
 */
public class Student1 {
    /**
     * 和数据库中的Student表对应
     */
    private Integer SID;
    private String Sname;
    private String Ssex;
    private Integer Sage;
    //省略的getter和setter方法

    public Integer getSID() {
        return SID;
    }

    public void setSID(Integer SID) {
        this.SID = SID;
    }

    public String getSname() {
        return Sname;
    }

    public void setSname(String sname) {
        Sname = sname;
    }

    public String getSsex() {
        return Ssex;
    }

    public void setSsex(String ssex) {
        Ssex = ssex;
    }

    public Integer getSage() {
        return Sage;
    }

    public void setSage(Integer sage) {
        Sage = sage;
    }

    @Override
    public String toString() {
        return "com.pojo{" +
                "SID=" + SID +
                ", Sname='" + Sname + '\'' +
                ", Ssex='" + Ssex + '\'' +
                ", Sage=" + Sage +
                '}';
    }
}

3.spring-mybatis.xml配置 

根据数据库信息注入数据源,并将相应的映射文件加载至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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="dataSource" class="com.mchange.v2.c3p0.DriverManagerDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--        数据源配置-->
        <property name="dataSource" ref="dataSource"></property>
<!--        加载mybatis配置文件-->
        <property name="configLocation" value="mybatis-config.xml"></property>
        <property name="mapperLocations" value="mapper/*.xml"></property>
    </bean>

<!--    获取Studentapper的代理对象-->
    <bean id="studentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
        <property name="mapperInterface" value="org.example.dao.StudentMapper"></property>
    </bean>
</beans>

4.测试

public class MybatisDemo {
    public static void main(String[] args) {
        String path = "spring-mybatis.xml";

        ClassPathXmlApplicationContext classContext = new ClassPathXmlApplicationContext(path);
        StudentMapper studentMapper  = (StudentMapper)classContext.getBean("studentMapper");
        Student1 student1 = studentMapper.selectStudentById(1);
        System.out.println(student1);
    }
}

 

Spring中JDBCTemplate的使用

jdbcTemplate操作步骤

导入相关依赖

      <!--spring支持jdbc模板操作-->
     <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.8.RELEASE</version>
     </dependency>

     <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.8.RELEASE</version>
     </dependency>

      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.39</version>
      </dependency>

 

JDBCTemplate的使用

public class JDBCTemplateDemo {
    public static void main(String[] args) {

        //创建对象,设置数据源信息
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/test");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("123456");

        //获取jdbc模板实例
        JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);

        //通过模板对象调用方法来执行相关操作
        //通过jdbcTemplate提供的update方法来完成变更操作(修改、新增、删除)
        //删除操作SQL
        String deleteSql = "delete from Student where SID = ?";
        int update = jdbcTemplate.update(deleteSql, new Object[]{22});
        System.out.println(update);

        //查询操作(单个对象) 使用queryForObject方法
        String selectSql1 = "select * from Student where SID = ?";
        Student1 student1 = jdbcTemplate.queryForObject(selectSql1, new Object[]{1}, new StudentMapper());
        System.out.println(student1);

        //查询操作(多个结果集对象) 使用query方法
        String selectSql2 = "select * from Student";
        List <Student1> student1List = jdbcTemplate.query(selectSql2, new StudentMapper());
        Iterator <Student1> iterator = student1List.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }
}

JDBCTemplate解决了JDBC结果集合Java代码的耦合性问题

实现一个RowMapper接口的实现类,手动完成数据库结果集和Java对象的映射

public class StudentMapper implements RowMapper<Student1> {
    @Override
    /**
     * jdbc模板能够完成自动映射为Java对象关键点在于实现RowMapper接口
     * 实现mapRow方法
     * ResultSet:数据库结果集
     * int :类似数据库数据序号,从0开始
     * 返回类型:指定的Java对象
     * 该方法主要是完成ResultSet结果集手动映射为Java对象
     *
     */
    public Student1 mapRow(ResultSet resultSet, int i) throws SQLException {
        Student1 student1 = new Student1();
        student1.setSID(resultSet.getInt("SID"));
        student1.setSage(resultSet.getString("Sage"));
        student1.setSname(resultSet.getString("Sname"));
        student1.setSsex(resultSet.getString("Ssex"));

        return student1;
    }
}

不管是单个结果集还是多个结果集都会代用到在RowMapper接口的实现类,数据库中每一条记录都会执行到mapRow方法。

 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring&Mybatis整合及Spring中JDBCTemplate的使用 的相关文章

随机推荐

  • PriorityQueue(优先级队列)的解读与底层实现

    目录 1 什么是优先级队列 xff1f 2 优先级队列的特性 3 如何使用优先级队列 4 JDK源码分析 4 1类的继承关系 4 2类的属性 4 3常用的方法 5 自定义优先级队列实现 5 1 优先级队列类定义 5 2 add 方法 5 3
  • HashMap的使用与底层结构剖析

    目录 一 基础概念 二 先使用再了解 三 底层结构 1 HashMap结构 xff08 JDK1 8以前 xff09 2 HashMap结构 xff08 JDK1 8以后 xff09 四 HashMap实现 1 成员变量 2 put实现 3
  • 线程基础与使用测试

    目录 一 进程和线程 二 线程的创建 1 继承Thread类 xff0c 重写run 方法 2 实现Runnable接口 xff0c 重写run方法 3 匿名线程 xff0c 匿名内部类 4 实现Callable接口 xff0c 重写cal
  • 线程生命周期及常用方法的使用

    一 守护线程 守护线程是什么 xff1f 守护线程是一类比较特殊的线程 xff0c 一般用于处理后台的工作 xff0c 比如JDK的垃圾回收线程 守护线程的作用 xff1f JVM xff08 Java Virtual Machine xf
  • git合并被fork的仓库的远程分支

    如果你 fork 了一个仓库并在自己的 forked 仓库中进行了更改 xff0c 而原始仓库也有一些更新 xff0c 此时想将原始仓库的更新合并到你的 forked 仓库 xff0c 可以按照以下步骤 xff1a 1 将原始仓库添加为远程
  • Linux-基础知识及常见操作命令汇总

    目录 1 终端操作 2 命令手册 3 关机重启 4 runlevel 5 目录结构 6 文件属性 7 Linux文件属主和属组 8 目录常用命令 9 VIM命令 10 进程管理命令 1 进程状态 2 ps命令 3 pstree命令 jobs
  • 关键字synchronized与volatile详解

    在多线程并发编程中synchronized和volatile都扮演着重要的角色 xff0c synchronized一直是元老级角色 xff0c 很多人都会称呼它为重量级锁 但是 xff0c 随着Java SE 1 6对synchroniz
  • 迁移学习与Transformer架构

    迁移学习 迁移学习干什么的 xff1f 迁移学习是通过从已学习的相关任务中转移知识来改进学习的新任务 Eg xff1a 学习识别苹果可能有助于识别梨 xff0c 学习骑自行车可能有助于学习骑摩托车 xff0c 学习打羽毛球可能有助于学习打网
  • 生产者消费者模型分析与实现

    生产者消费者模式就是通过一个容器来解决生产者和消费者的强耦合问题 生产者和消费者彼此之间不直接通讯 xff0c 而通过阻塞队列来进行通讯 xff0c 所以生产者生产完数据之后不用等待消费者处理 xff0c 直接扔给阻塞队列 xff0c 消费
  • ConcurrentHashMap优点与源码剖析

    哈希表是中非常高效 xff0c 复杂度为O 1 的数据结构 xff0c 在Java开发中 xff0c 我们最常见到最频繁使用的就是HashMap和HashTable xff0c 但是在线程竞争激烈的并发场景中使用都不够合理 HashMap
  • IO-字节流

    文件 amp File类的使用 1 文件的概念 文件可以分为文本文件 二进制文件 2 IO流的概念 流是有顺序 有起点和终点的集合 xff0c 是对数据传输的总称 流的本质就是用来对数据进行操作 IO是我们实现的目的 xff0c 实现这个目
  • STM32F407的TCP编程出现客户端无法连接上服务器,DHCP获取IP失败,服务器重启客户端无法自动重连问题解决方案

    单写一篇文章记录这些问题 xff0c 因为有的问题实在是困扰了我太久太久了 xff0c 终于解决了 xff01 xff01 xff01 1 STM32F407的TCP编程 xff0c TCP SERVER测试完全正常 xff0c TCP C
  • SQL练习汇总(查询“01“课程比“02“课程成绩高的学生的信息及课程分)

    1 学生表 Student SID Sname Sage Ssex SID 学生编号 Sname 学生姓名 Sage 年龄 Ssex 学生性别 编号 姓名 年龄 性别 1 赵雷 20 男 2 钱电 20 男 3 孙风 21 男 4 吴兰 1
  • JDBC编程,SQL注入与连接池

    JDBC概念 JDBC Java Data Base Conection 是java中提供的一套标准的应用编程接口 xff0c 用来连接Java编程语言和数据库 JDBC常用组件 xff1a DriverManger xff1a 数据库驱动
  • Pytorch搭建基于SRCNN图像超分辨率重建模型及论文总结

    SRCNN xff08 Super Resolution Convolutional Neural Network xff09 论文出处 xff1a Learning a Deep Convolutional Network for Ima
  • 技术领域的面试总结

    在当今互联网中 xff0c 虽然互联网行业从业者众多 xff0c 不断崛起的互联网公司也会很多 xff0c 仍然是很多同学想要进入的企业 那么本篇文章将会为大家很直白的讲解面试流程以及侧重点 仔细阅读本篇文章 xff0c 绝对会有所收获 x
  • Mybatis基于XML与基于注解实现CRUD

    数据库 实体类Student package com pojo Description Created by Resumebb Date 2021 3 26 public class Student 和数据库中的STudent表对应 pri
  • Spring-IOC容器进行对象管理

    目录 IOC概念 IOC思想 Spring管理对象 集成依赖 spring的配置文件 xff08 Applicationcontext xml xff09 创建实体类User Spring对Bean的实例化方式 基于配置形式 1 通过无参构
  • Spring-AOP原理及实现

    Spring AOP AOP Aspect Oriented Programing 面向切面编程 xff1a 扩展功能不通过修改源代码实现 AOP采用横向抽取机制 xff0c 取代传统纵向继承体系实现响应的功能 xff08 性能监控 事务
  • Spring&Mybatis整合及Spring中JDBCTemplate的使用

    Spring和Mybatis整合 在mybatis中 xff0c 操作数据库需要获取到SQLSession对象 xff0c 而该对象的实例过程在mybatis是通过SQLSessionFactoryBuilder读取全局配置文件来实例化一个