Java课题笔记~ Spring 集成 MyBatis

Spring 集成 MyBatis

将 MyBatis 与 Spring 进行整合,主要解决的问题就是将 SqlSessionFactory 对象交由 Spring 来管理。所以该整合,只需要将 SqlSessionFactory 的对象生成器SqlSessionFactoryBean 注册在 Spring 容器中,再将其注入给 Dao 的实现类即可完成整合。

实现 Spring 与 MyBatis 的整合常用的方式:扫描的 Mapper 动态代理

Spring 像插线板一样,mybatis 框架是插头,可以容易的组合到一起。

插线板 spring 插上 mybatis,两个框架就是一个整体。

1、MySQL 创建数据库 db1,新建表 student2

 

2、maven 依赖 pom.xml

<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.26</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.3.26</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.26</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.11</version></dependency><!-- Spring整合MyBatis的依赖 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.1.0</version></dependency><!-- --------------------- --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.8</version></dependency>
</dependencies>	<!--插件:-->
<build><resources><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.11.0</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins>
</build>

3、定义实体类 Student

 代码如下:

package com.ambow.pojo;import lombok.Data;@Data
public class Student {private int id;private String name;private int age;}

4、定义 StudentDao 接口

 代码如下:

package com.ambow.dao;import com.ambow.pojo.Student;import java.util.List;public interface StudentDao {int insertStudent(Student student);int updateStudent(Student student);int deleteStudent(int id);Student selectStudentById(int id);List<Student> selectAllStudents();
}

5、定义映射文件 mapper

在 Dao 接口的包中创建 MyBatis 的映射文件 mapper,命名与接口名相同,本例为 StudentDao.xml

mapper 中的 namespace 取值也为 Dao 接口 的全限定性名。

  代码如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ambow.dao.StudentDao"><insert id="insertStudent">insert into student2 values(null,#{name},#{age})</insert><update id="updateStudent">update student2 set name = #{name},age = #{age} where id = #{id}</update><delete id="deleteStudent">delete from student2 where id = #{id}</delete><select id="selectStudentById" resultType="com.ambow.pojo.Student">select * from student2 where id = #{id}</select><select id="selectAllStudents" resultType="com.ambow.pojo.Student">select * from student2</select></mapper>

6、定义 Service 接口和实现类

接口定义:

  代码如下:

package com.ambow.service;import com.ambow.pojo.Student;import java.util.List;public interface StudentService {int addStudent(Student student);int modifyStudent(Student student);int removeStudent(int id);Student findStudentById(int id);List<Student> findAllStudents();
}

实现类定义:

  代码如下:

package com.ambow.service.impl;import com.ambow.dao.StudentDao;
import com.ambow.pojo.Student;
import com.ambow.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.List;@Service("studentService")
public class StudentServiceImpl implements StudentService {//引入StudentDao的对象@Autowiredprivate StudentDao studentDao;public void setStudentDao(StudentDao studentDao) {this.studentDao = studentDao;}@Overridepublic int addStudent(Student student) {return studentDao.insertStudent(student);}@Overridepublic int modifyStudent(Student student) {return studentDao.updateStudent(student);}@Overridepublic int removeStudent(int id) {return studentDao.deleteStudent(id);}@Overridepublic Student findStudentById(int id) {return studentDao.selectStudentById(id);}@Overridepublic List<Student> findAllStudents() {return studentDao.selectAllStudents();}
}

7、定义 MyBatis 主配置文件

在 src 下定义 MyBatis 的主配置文件,命名为 mybatis.xml

这里有两点需要注意:

(1)主配置文件中不再需要数据源的配置了。因为数据源要交给 Spring 容器 来管理了。

(2)这里对 mapper 映射文件的注册,使用标签,即只需给出 mapper 映射文件所在的包即可。因为 mapper 的名称与 Dao 接口名相同, 可以使用这种简单注册方式。

这种方式的好处是:若有多个映射文件,这里的 配置也是不用改变的。当然,也可使用原来的标签方式。

 

8 、修改 Spring 配置文件

(1) 数据源的配置(掌握)

使用 JDBC 模板,首先需要配置好数据源,数据源直接以 Bean 的形式配置 在 Spring 配置文件中。根据数据源的不同,其配置方式不同:

Druid 数据源 DruidDataSource Druid 是阿里的开源数据库连接池。是 Java 语言中最好的数据库连接 池。Druid 能够提供强大的监控和扩展功能。Druid 与其他数据库连接池的 最大区别是提供数据库的

官网:GitHub - alibaba/druid: 阿里云计算平台DataWorks(https://help.aliyun.com/document_detail/137663.html) 团队出品,为监控而生的数据库连接池阿里云计算平台DataWorks(https://help.aliyun.com/document_detail/137663.html) 团队出品,为监控而生的数据库连接池 - GitHub - alibaba/druid: 阿里云计算平台DataWorks(https://help.aliyun.com/document_detail/137663.html) 团队出品,为监控而生的数据库连接池https://github.com/alibaba/druid

使用地址:Home · alibaba/druid Wiki · GitHub阿里云计算平台DataWorks(https://help.aliyun.com/document_detail/137663.html) 团队出品,为监控而生的数据库连接池 - Home · alibaba/druid Wikihttps://github.com/alibaba/druid/wiki/

常见问题

配置连接池:

  Spring 配置文件:

  代码如下:

    <!--1.DataSource--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean>

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

为了便于维护,可以将数据库连接信息写入到属性文件中,使 Spring 配置 文件从中读取数据。

属性文件名称自定义,但一般都是放在 src 下。

  代码如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.2.111:3306/db1
jdbc.username=root
jdbc.password=Mysql666!

Spring 配置文件从属性文件中读取数据时,需要在的 value 属性中使用${ },将在属性文件中定义的 key 括起来,以引用指定属性的值。

该属性文件若要被 Spring 配置文件读取,其必须在配置文件中进行注册。 使用<context>标签。

<context:property-placeholder />方式(掌握)

该方式要求在 Spring 配置文件头部加入 spring-context.xsd 约束文件

<context:property-placeholder />标签中有一个属性 location,用于指定属 性文件的位置。

 (3) 注册 SqlSessionFactoryBean

 

代码如下: 

    <!--2.注册SqlSessionFactoryBean--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="typeAliasesPackage" value="com.ambow.pojo" /><property name="mapperLocations" value="classpath:com/ambow/dao/*.xml" /></bean>

(4) 定义 Mapper 扫描配置器 MapperScannerConfigurer

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

 

 代码如下:

    <!--3.mapper的扫描配置器 -> 生成mapper的代理对象--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /><property name="basePackage" value="com.ambow.dao" /></bean>

9、向 Service 注入接口名

向 Service 注入 Mapper 代理对象时需要注意,由于通过 Mapper 扫描配置器 MapperScannerConfigurer 生成的 Mapper 代理对象没有名称,所以在 向 Service 注入 Mapper 代理时,无法通过名称注入。但可通过接口的简单类名注入,因为生成的是这个 Dao 接口的对象。

 

 代码如下:

    <!--4.向service层注入Dao-->
<!--    <bean id="studentService" class="com.ambow.service.impl.StudentServiceImpl"><property name="studentDao" ref="studentDao" /></bean>-->

10、Spring 配置文件全部配置

 代码如下:

<?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"><!--整合:把MyBatis中的核心对象,放到Spring容器--><!--引入属性配置文件--><context:property-placeholder location="classpath:jdbc.properties" /><context:component-scan base-package="com.ambow.service" /><!--1.DataSource--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><!--2.注册SqlSessionFactoryBean--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="typeAliasesPackage" value="com.ambow.pojo" /><property name="mapperLocations" value="classpath:com/ambow/dao/*.xml" /></bean><!--3.mapper的扫描配置器 -> 生成mapper的代理对象--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /><property name="basePackage" value="com.ambow.dao" /></bean><!--4.向service层注入Dao-->
<!--    <bean id="studentService" class="com.ambow.service.impl.StudentServiceImpl"><property name="studentDao" ref="studentDao" /></bean>--><!--注入的过程--><!--dataSource -> SqlSessionFactoryBean -> MapperScannerConfigurer(生成Dao代理对象) -> studentService--></beans>

项目整体结构如下图:

 运行测试类test02:

 

运行测试类test03:

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/34643.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux 搭建Minio

第一步&#xff1a;创建&#xff1a;/xxx/xxx/minio 第二步&#xff1a;在创建&#xff1a;/xxx/xxx/data 第三步&#xff1a; Minio下载网址: https://min.io/download#/linux 然后将这个文件放入你刚刚创建的文件夹 第四步&#xff1a;配置环境变量把Minio的账号密码配置一…

多目标优化算法之樽海鞘算法(MSSA)

樽海鞘算法的主要灵感是樽海鞘在海洋中航行和觅食时的群聚行为。相关文献表示&#xff0c;多目标优化之樽海鞘算法的结果表明&#xff0c;该算法可以逼近帕雷托最优解&#xff0c;收敛性和覆盖率高。 通过给SSA算法配备一个食物来源库来解决第一个问题。该存储库维护了到目前为…

Docker镜像查看下载删除镜像文件的相关命令

1.镜像相关命令 本地查看有哪些镜像文件&#xff1a; docker images镜像的名称就是我们常见的一些软件&#xff0c;镜像相当于把软件和软件所需要的运行环境打包到一个镜像文件里面&#xff0c;将来在通过这个镜像文件创建出对应的容器&#xff0c;容器有了以后这些软件自动的…

java线程的优先级、守护线程的概念

1.线程的调度 抢占式调度 非抢占式调度 1.1 抢占式调度 优先级越高&#xff0c;抢到cpu的概率越高 1.2 守护线程 守护线程&#xff0c;非守护线程。当其他的非守护线程执行完毕以后&#xff0c;守护线程会陆续结束。 守护线程的应用场景

【Linux】网络协议总结

目录 网络协议总结 应用层 传输层 网络层 数据链路层 网络协议总结 应用层 应用层的作用&#xff1a;负责应用程序间沟通&#xff0c;完成一系列业务处理所需服务。能够根据自己的需求&#xff0c;设计对应的应用层协议。了解HTTP协议。理解DNS的原理和工作流程。 传…

插入排序(Java实例代码)

目录 插入排序 一、概念及其介绍 二、适用说明 三、过程图示 四、Java 实例代码 InsertionSort.java 文件代码&#xff1a; 插入排序 一、概念及其介绍 插入排序(InsertionSort)&#xff0c;一般也被称为直接插入排序。 对于少量元素的排序&#xff0c;它是一个有效的算…

CNN(四):ResNet与DenseNet结合--DPN

&#x1f368; 本文为&#x1f517;365天深度学习训练营中的学习记录博客&#x1f356; 原作者&#xff1a;K同学啊|接辅导、项目定制 前面实现了ResNet和DenseNet的算法&#xff0c;了解了它们有各自的特点&#xff1a; ResNet&#xff1a;通过建立前面层与后面层之间的“短路…

Nginx中间件安全基线配置与操作指南-翻译

1、日志配置 安全基线项目名称 Nginx日志审计安全基线要求项 安全基线编号 Nginx-001 安全基线项说明 配置Nginx日志记录和审核 设置操作步骤 (1)编辑 nginx.conf 配置文件 将 error_log 前的“#”去掉&#xff0c;记录错误日志&#xff1b; 将 access_log 前的“#”去…

云原生核心原则和特征

云原生&#xff08;Cloud Native&#xff09;是一种软件开发和部署方法论&#xff0c;旨在充分利用云计算的优势来构建和管理应用程序。云原生应用程序是专为在云环境中设计、构建和运行的应用程序。 以下是云原生的一些核心原则和特征&#xff1a; 微服务架构&#xff1a;云…

TSINGSEE青犀视频安防监控视频平台EasyCVR设备在线,视频无法播放的原因排查

可支持国标GB28181、RTMP、RTSP/Onvif、海康Ehome、海康SDK、大华SDK、宇视SDK等多种协议接入的安防监控视频平台EasyCVR基于云边端一体化架构&#xff0c;具有强大的数据接入、处理及分发能力&#xff0c;可在复杂的网络环境中&#xff0c;将分散的各类视频资源进行统一汇聚、…

IDEA全局设置MyBatis中写SQL语句提示

第一步&#xff1a;把这两个设置改成MySQL即可&#xff1a; 第二步&#xff1a;找到设置>编辑器>语言注入>店家加号&#xff0c;选择MySQL

微信小程序在使用vant组件库时构建npm报错

在跟着vant官方进行使用步骤一步步操作时&#xff0c;由于要构建NPM&#xff0c;但NPM包在App配置文件的外部 所以在做下图这一步时&#xff1a; 接着再进行npm构建时会报错 message:发生错误 Error: F:\前端学习\前端框架\小程序\project\demo\miniprogram解决方法 &#xf…

Linux Centos 8 用户管理之重置密码

如果在使用linux系统时遇到系统密码问题无法进入系统或者操作的时候可以按照下面的方法重置用户密码。 一、root用户密码重置&#xff1a; 方式一&#xff1a; 1.重启电脑或虚拟机&#xff0c;在刚进引导界面时候按“e"键&#xff0c;进入编辑模式。 2.在”quiet"…

Java:正则表达式书写规则及相关案例:检验QQ号码,校验手机号码,邮箱格式,当前时间

正则表达式 目标:体验一下使用正则表达式来校验数据格式的合法性。需求:校验QQ号码是否正确&#xff0c;要求全部是数字&#xff0c;长度是(6-20&#xff09;之间&#xff0c;不能以0开头 首先用自己编写的程序判断QQ号码是否正确 public static void main(String[] args) {Sy…

递归、搜索与回溯算法

一.递归 &#xff08;1&#xff09;汉诺塔问题 当n2时&#xff0c;要将A中最下面盘子上方的盘子放到B上&#xff0c;最下面盘子放到C上&#xff0c;再将B上的盘子通过A放到C即可&#xff1b; 当n3时&#xff0c;要将A中最下面盘子上方的盘子放到B上&#xff0c;最下面盘子放到…

如何通过nginx反向代理实现不同域名映射到同一台服务器的相同端口

要在Nginx中实现不同域名映射到同一台服务器的相同端口&#xff0c;您可以使用Nginx的代理转发技术。 首先&#xff0c;您需要了解Nginx的代理转发工作原理。Nginx的代理转发是指在代理服务器&#xff08;proxy server&#xff09;收到一个请求时&#xff0c;先将请求转发给目…

Spark2.2出现异常:ERROR SparkUI: Failed to bind SparkUI

详细错误信息如下&#xff1a; 复制代码 19/03/19 11:04:18 INFO util.log: Logging initialized 5402ms 19/03/19 11:04:18 INFO server.Server: jetty-9.3.z-SNAPSHOT 19/03/19 11:04:18 INFO server.Server: Started 5604ms 19/03/19 11:04:18 WARN util.Utils: Service ‘S…

uniapp 小兔鲜儿 - 首页模块(1)

目录 自定义导航栏 静态结构 安全区域​ 通用轮播组件 静态结构 自动导入全局组件 全局组件类型声明 .d.ts文件 注册组件 vue/runtime-core 首页 – 轮播图指示点 首页 – 获取轮播图数据 首页 – 轮播图数据类型并渲染 首页 – 轮播图总结 首页分类 首页 – 前…

电影评论:二分类

跟着《python深度学习》做了个书上小项目&#xff0c;现在总结下该项目内容。 获取数据(这里获取的是IMDB数据集&#xff0c;其中有train_data和train_label两个标签&#xff0c;train_data&#xff1a;英文句子&#xff0c;train_label&#xff1a;正/负面(0,1)) from keras.d…

Jupyter Notebook 遇上 NebulaGraph,可视化探索图数据库

在之前的《手把手教你用 NebulaGraph AI 全家桶跑图算法》中&#xff0c;除了介绍了 ngai 这个小工具之外&#xff0c;还提到了一件事有了 Jupyter Notebook 插件: https://github.com/wey-gu/ipython-ngql&#xff0c;可以更便捷地操作 NebulaGraph。 本文就手把手教你咋在 J…