(八)Spring与MyBatis整合

持久层

目录

  • Mybatis 开发步骤回顾
  • Mybatis 开发中存在的问题
  • Spring 与 Mybatis 整合思路
  • Spring 与 Mybatis 整合的开发步骤
  • Spring 与 Mybatis 整合的编码
  • 搭建开发环境 pom.xml
  • Spring 配置文件的配置
  • 编码
  • Spring 与 Mybatis 整合细节

持久层整合总述

1、Spring 框架为什么要与持久层技术进行整合?

  • JavaEE开发需要持久层进行数据库的访问操作
  • JDBC、Hibernate、MyBatis 进行持久开发过程存在大量的代码冗余
  • Spring 基于模板设计模式对于上述的持久层技术进行了封装

2、Spring 可以与哪些持久层技术进行整合?

  • JDBC —— JDBCTemplate
  • Hibernate(JPA)—— HibernateTemplate
  • MyBatis —— SqlSessionFactoryBeanMapperScannerConfigure

Mybatis 开发步骤回顾

  1. 实体类 User
public class User implements Serializable {private Integer id;private String name;private String password;public User() {}public User(Integer id, String name, String password) {this.id = id;this.name = name;this.password = password;}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 getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}
  1. 实体别名 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Confi 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><typeAliases><typeAlias alias="user" type="com.yusael.mybatis.User"/></typeAliases><environments default="mysql"><environment id="mysql"><transactionManager type="JDBC"></transactionManager><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/yus?useSSL=false"/><property name="username" value="root"/><property name="password" value="1234"/></dataSource></environment></environments>
</configuration>
  1. 表 t_users
create table t_users values (id int(11) primary key auto_increment,name varchar(12),password varchar(12)
);
  1. 创建 DAO 接口:UserDAO
public interface UserDAO {public void save(User user);
}
  1. 实现Mapper文件:UserDAOMapper.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="com.yusael.mybatis.UserDAO"><insert id="save" parameterType="user">insert into t_users(name, password) values (#{name}, #{password})</insert>
</mapper>
  1. 注册 Mapper 文件 mybatis-config.xml
<mappers><mapper resource="UserDAOMapper.xml"/>
</mappers>
  1. MybatisAPI 调用
public class TestMybatis {public static void main(String[] args) throws IOException {InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession session = sqlSessionFactory.openSession();UserDAO userDAO = session.getMapper(UserDAO.class);User user = new User();user.setName("yusael");user.setPassword("123456");userDAO.save(user);session.commit();}
}

Mybatis 开发中存在的问题

问题:配置繁琐、代码冗余

1. 实体
2. 实体别名					配置繁琐
3. 表
4. 创建 DAO 接口
5. 实现 Mapper 文件
6. 注册 Mapper 文件			配置繁琐
7. Mybatis API 调用			代码冗余

Spring 与 Mybatis 整合思路

在这里插入图片描述
在这里插入图片描述

Spring 与 Mybatis 整合的开发步骤

  • 配置文件(ApplicationContext.xml)进行相关配置(只需要配置一次

  • 编码
    1.实体类
    2.表
    3.创建DAO接口
    4.Mapper文件配置

Spring 与 Mybatis 整合的编码

搭建开发环境 pom.xml

<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.6.RELEASE</version>
</dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.4</version>
</dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.12</version>
</dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.43</version>
</dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.4</version>
</dependency>

Spring 配置文件的配置

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!--连接池--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/yus?useSSL=false"/><property name="username" value="root"/><property name="password" value="1234"/></bean><!--创建SqlSessionFactory SqlSessionFactoryBean--><bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><!-- 指定实体类所在的包 --><property name="typeAliasesPackage" value="com.yusael.entity"/><!--指定配置文件(映射文件)的路径,还有通用配置--><property name="mapperLocations"><list><value>classpath:com.yusael.dao/*Mapper.xml</value></list></property></bean><!--创建DAO对象 MapperScannerConfigure--><bean id="scanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/><!--指定DAO接口放置的包--><property name="basePackage" value="com.yusael.dao"/></bean></beans>

编码

  1. 实体 com.yusael.entity.User
public class User implements Serializable {private Integer id;private String name;private String password;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 getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}
  1. 表 t_user
create table t_users values (id int(11) primary key auto_increment,name varchar(12),password varchar(12)
);
  1. DAO接口 com.yusael.dao.UserDAO
public interface UserDAO {public void save(User user);
}
  1. Mapper文件配置 resources/applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!--连接池--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/yus?useSSL=false"/><property name="username" value="root"/><property name="password" value="1234"/></bean><!--创建SqlSessionFactory SqlSessionFactoryBean--><bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="typeAliasesPackage" value="com.yusael.entity"/><property name="mapperLocations"><list><value>classpath:com.yusael.dao/*Mapper.xml</value></list></property></bean><!--创建DAO对象 MapperScannerConfigure--><bean id="scanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/><property name="basePackage" value="com.yusael.dao"/></bean></beans>

 

  1. 测试
/*** 用于测试: Spring 与 Mybatis 的整合*/
@Test
public void test() {ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");UserDAO userDAO = (UserDAO) ctx.getBean("userDAO");User user = new User();user.setName("xiaojr");user.setPassword("999999");userDAO.save(user);
}

Spring 与 Mybatis 整合细节

问题:Spring 与 Myabatis 整合后,为什么 DAO 不提交事务,但是数据能够插入数据库中?

  1. Mybatis 提供的连接池对象 —> 创建 Connection
    Connection.setAutoCommit(false) 手工的控制了事务,操作完成后,需要手工提交。
  2. Druid(C3P0、DBCP)作为连接池 —> 创建 Connection
    Connection.setAutoCommit(true) 默认值为 true,保持自动控制事务,一条 sql 自动提交。

答案:因为 Spring 与 Mybatis 整合时,引入了外部连接池对象,保持自动的事务提交这个机制Connection.setAutoCommit(true),不需要手工进行事务的操作,也能进行事务的提交。

注意:实战中,还是会手工控制事务(多条SQL一起成功,一起失败),后续 Spring 通过 事务控制 解决这个问题。

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

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

相关文章

Git 企业开发者教程

为什么要写这样一个面向企业开发者的Git教程&#xff1f;这个问题也困扰我自己很久。其实我使用git的时间也不短了&#xff0c;但是就和正在阅读本文的每一位一样&#xff0c;常用的基本就是那么几个(git clone, git push)等等。然而git其实有着非常强大的功能&#xff0c;如果…

P1169-[ZJOI2007]棋盘制作【贪心】

正题 题目链接:https://www.luogu.org/problemnew/show/P1169 题目大意 一个矩阵中求一个最大的子矩阵和子正方形使得它们其中都是01交错。 解题思路 lefti,jleft_{i,j}lefti,j​表示(i,j)(i,j)(i,j)往左扩展多远&#xff0c;righti,jright_{i,j}righti,j​表示(i,j)(i,j)(i,…

(九)Spring 事务开发、事务属性详解

持久层 目录 事务回顾Spring 控制事务的开发Spring 中的事务属性&#xff08;Transaction Attribute&#xff09;隔离属性&#xff08;ISOLATION&#xff09;传播属性&#xff08;PROPAGATION&#xff09;只读属性&#xff08;readOnly&#xff09;超时属性&#xff08;timeo…

基于百度理解与交互技术实现机器问答

一、前言我们都知道现在聊天对话机器是一个很有意思的东西&#xff0c;比如说苹果siri&#xff0c;比如说微软的小冰。聊天对话机器的应用场景也很广泛&#xff0c;比如说&#xff1a;银行的自助办卡机器人、展会讲解解说等等。我们对机器人说句话&#xff0c;机器人从听取&…

Spark入门(十七)之单表关联

一、单表关联 给出child-parent&#xff08;孩子——父母&#xff09;表&#xff0c;要求输出grandchild-grandparent&#xff08;孙子——祖父母&#xff09;表 二、maven设置 <?xml version"1.0" encoding"UTF-8"?><project xmlns"htt…

P3514-[POI2011]LIZ-Lollipop【思路题】

正题 题目链接:https://www.luogu.org/problemnew/show/P3514 题目大意 一个12序列&#xff0c;若干个询问求有没有一个子串之和为kkk 解题思路 首先感谢ZYCdalaoZYCdalaoZYCdalao的温馨提示。 然后进入正题 首先我们考虑一个串的和为kkk 那么最边的数的情况(1,1),(1,2),(2…

(十)Spring 与 MVC 框架整合

Spring 整合 MVC 目录 MVC 框架整合思想为什么要整合 MVC 框架搭建 Web 运行环境Spring 整合 MVC 框架的核心思路1. 准备工厂2. 代码整合Spring 整合 Struts2MVC 框架整合思想 为什么要整合 MVC 框架 MVC 框架提供了控制器&#xff08;Controller&#xff09;调用 Servlet …

Spark入门(十八)之多表关联

一、多表关联 输入是两个文件&#xff0c;一个代表工厂表&#xff0c;包含工厂名列和地址编号列&#xff1b;另一个代表地址表&#xff0c;包含地址名列和地址编号列。要求从输入数据中找出工厂名和地址名的对应关系&#xff0c;输出"工厂名——地址名"表 二、maven…

利用VSTS跟Kubernetes整合进行CI/CD

为什么VSTS要搭配Kubernetes&#xff1f;通常我们在开发管理软件项目的时候都会碰到一个很头痛的问题&#xff0c;就是开发、测试、生产环境不一致&#xff0c;导致开发人员和测试人员甚至和运维吵架。因为常见的物理环境甚至云环境中&#xff0c;这些部署环境都是由运维人员提…

P3112-[USACO14DEC]后卫马克Guard Mark【贪心】

正题 题目链接:https://www.luogu.org/problemnew/show/P3112 题目大意 有nnn只牛&#xff0c;每只牛有hi,wi,sih_i,w_i,s_ihi​,wi​,si​分别表示有多高&#xff0c;有多重&#xff0c;上面最多承载总共多重的牛。 选择一些牛依次摆放要求高度超过TTT且上面还能增加最重的物…

(十一)Spring 基础注解(对象创建相关注解、注入相关注解)

注解编程 目录 注解基础概念注解的作用Spring 注解的发展历程Spring 基础注解&#xff08;Spring 2.x&#xff09;对象创建相关注解ComponentRepository、Service、ContollerScopeLazy生命周期注解 PostConstruct、PreDestroy注入相关注解用户自定义类型 AutowiredJDK 类型注…

Spark Streaming之统计socket单词数

一、统计socket单词数 侦听TCP套接字的数据服务器接收到的文本数据中的单词数。 二、maven配置 <?xml version"1.0" encoding"UTF-8"?><project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/…

使用 ASP.NET Core, Entity Framework Core 和 ABP 创建N层Web应用 第二篇

介绍这是“使用 ASP.NET Core &#xff0c;Entity Framework Core 和 ASP.NET Boilerplate 创建N层 Web 应用”系列文章的第二篇。以下可以看其他篇目&#xff1a;使用 ASP.NET Core &#xff0c;Entity Framework Core 和 ASP.NET Boilerplate 创建N层 Web 应用 第一篇 &…

jzoj4786-[NOIP2016提高A组模拟9.17]小a的强迫症【数论】

正题 题目大意 nnn个颜色第iii个个数为numinum_inumi​个&#xff0c;然后要求第iii种颜色的最后一个一定在第i1i1i1种的最后一个前面。求方案总数。 解题思路 首先先定义一个1∼n1\sim n1∼n的序列&#xff0c;然后依次将剩下的数插入。 第iii个颜色有z(∑j1i−1numj)1z(\su…

0-MyBatis简介

MyBatis简介 目录 简介MyBatis 历史MyBatis特点为什么要使用 MyBatis&#xff1f;JDBC 缺点Hibernate 缺点MyBatis简介 MyBatis 历史 MyBatis 原是 apache 的一个开源项目 iBatis&#xff1b;2010年6月这个项目由 apache software foundation 迁移到了 google code&#xf…

揭秘微软6万工程师DevOps成功转型的技术「武器」

在微软&#xff0c;通过其自身数年的 DevOps 转型&#xff0c; 6 万名工程师实现了更好的软件平台创新和快速迭代。微软有庞大的技术产品矩阵&#xff0c;同时也具有每天发布的能力&#xff0c;其中&#xff0c;微软研发云是支撑整个开发过程与运维最重要的基础平台。微软研发云…

jzoj4787-[NOIP2016提高A组模拟9.17]数格子【矩阵乘法】

正题 题目大意 求121\times 212的方块铺满4n4\times n4n的方格方案总数。 解题思路 首先 当计算fnf_nfn​时&#xff0c; 显然最后一排可以(−−−−)(∣∣∣∣)(−−∣∣)(∣−−∣)(∣∣−−)(--\ --)(|\ \ |\ \ |\ \ |)(--\ \ |\ \ |)(|\ \ --\ \ |)(|\ \ |--)(−− −−)…

Flowable学习笔记(一、入门)

转载自 Flowable学习笔记&#xff08;一、入门&#xff09; 一、Flowable简介 1、Flowable是什么 Flowable是一个使用Java编写的轻量级业务流程引擎。Flowable流程引擎可用于部署BPMN 2.0流程定义&#xff08;用于定义流程的行业XML标准&#xff09;&#xff0c; 创建这些流…

01-MyBatis入门程序

MyBatis入门程序 目录 1. 下载 Mybatis 核心包2. 创建工程&#xff0c;引入 MyBatis 核心包及依赖包3. 创建 customer 表&#xff0c;建立与表对应的 domain使用 lombok&#xff0c;开启注解创建 Customer 类4. 创建 MyBatis 核心配置文件 SqlMappingConfig.xml5. 创建表对象…

角落的开发工具集之Vs(Visual Studio)2017插件推荐

“ 工具善其事&#xff0c;必先利其器&#xff01;装好这些插件让vs更上一层楼”因为最近录制视频的缘故&#xff0c;很多朋友都在QQ群留言&#xff0c;或者微信公众号私信我&#xff0c;问我一些工具和一些插件啊&#xff0c;怎么使用的啊&#xff1f;那么今天我忙里偷闲整理一…