17-Spring持久层框架整合

article/2025/8/13 9:39:47

上一篇:16-Spring 基于注解的AOP编程、AOP总结https://blog.csdn.net/fsjwin/article/details/109482768

1.为什么Spring要与持久层框架进行整合

spring是一个优秀的框架,他的优秀支持就是能整合所有程序员想要让他整合的框架,这里所说的持久成也不例外。

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

2.Spring要可以与那些持久层框架进行整合

  1. jdbc JdbcTemplate
  2. Hibernate (JPA) HibernateTemplate
  3. Mybatis SqlSessionFactoryBean、MapperScannerConfiger

3.Mybatis开发回顾,在Spring没有整合前

  1. 实体
  2. 实体别名
  3. 创建DAO接口
  4. 实现Mapper文件(对maper编程)
  5. 注册Mapper文件
  6. MyBatisApi调用

3.1 实体 User.java

package mybatis;import java.io.Serializable;/*** @author yuhl* @Date 2020/11/4 10:51* @Classname User* @Description 1. 实体*/
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;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", password='" + password + '\'' +'}';}
}

3.2. 实体别名mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><typeAliases><!-- 2. 实体别名--><typeAlias alias="user" type="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/yuhl?useSSL=false"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers></mappers>
</configuration>

在这里插入图片描述

3.3. 表

在这里插入图片描述


-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (`id` int(0) NOT NULL AUTO_INCREMENT,`name` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,`password` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

3.4. 创建DAO接口 UserDao.java

package mybatis;/*** @author yuhl* @Date 2020/11/4 10:59* @Classname UserDao* @Description TODO*/
public interface UserDao {//保存用户public void save(User user);
}

3.5. 实现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="mybatis.UserDao"> <!--接口名--><!--id:mybatis.UserDao接口中的方法面parameterType:面向对象的对象名字--><insert id="save" parameterType="user">insert into t_user(name,password) value (#{name},#{password})</insert>
</mapper>

3.6. 注册Mapper文件UserDAOMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><typeAliases><!-- 2. 实体别名--><typeAlias alias="user" type="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/yuhl?useSSL=false"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><!--注册mapper.xml到mybatis--><mapper resource="UserDAOMapper.xml"/></mappers>
</configuration>

在这里插入图片描述

3.7. MyBatisApi调用

import mybatis.User;
import mybatis.UserDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;import java.io.IOException;
import java.io.InputStream;/*** @author yuhl* @Date 2020/11/4 11:06* @Classname MybatisTest* @Description 测试*/
public class MybatisTest {@Testpublic void test1(){try {//通过流加载mybatis的主配置文件:mybatis-config.xmlInputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");//SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserDao userDao = sqlSession.getMapper(UserDao.class);userDao.save(new User("yuhl", "222222"));sqlSession.commit();sqlSession.close();} catch (IOException e) {e.printStackTrace();}}
}

插入成功:
在这里插入图片描述

3.单纯的Mybatis编程存在的问题

  1. 配置繁琐 第2步和第7步
    如果有9999个类该怎办?
    在这里插入图片描述
  2. 代码冗余
    主要指的是API代码冗余 。
    在这里插入图片描述
    由于以上两个原因,我们不会使用mybatis单独做开发,会使用spring对于mybatis的整合,下面看对于整合后的mybitis的使用是不是更为丝滑呢!
    即spring可以积极2.6.7三个步骤的问题。

4.Spring的Mybatis整合

1. 实体
2. 实体别名(<property name="typeAliasesPackage" value="com.yuhl.entity"/>)
3. 表
4. 创建DAO接口
5. 实现Mapper文件(对maper编程)
6. 注册Mapper文件(<value>classpath:com.yuhl.mapper/*DAOMapper.xml</value>)
7. MyBatisApi调用(被优化了直接从factory.getBean("userDAO"))
以上步在使用spring整合后1. 实体2. 表3. 创建DAO接口4. 实现Mapper文件(对maper编程)

引入jar包:pom.xml 特别注意与mybatis整合是使用druid连接池

<?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"><parent><artifactId>spring5_20201031</artifactId><groupId>org.yuhl</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>Spring_mybatis</artifactId><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.1.14.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.1.14.RELEASE</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.2</version></dependency><!--阿里巴巴连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.18</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.48</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.6</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-context --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.4.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.1.14.RELEASE</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.8.8</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.3</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.25</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency></dependencies></project>

4.1在mybatis-config.xml中的有所东西均可以在applicationContex.xml配置消灭mybatis-config.xml

在这里插入图片描述
在这里插入图片描述
至此可以完全消灭mybatis-config.xml文件。仅使用applicationContex.xml

4.1 代码如下

  1. 实体User .java
package com.yuhl.entity;import java.io.Serializable;/*** @author yuhl* @Date 2020/11/4 10:51* @Classname User* @Description 1. 实体*/
public class User implements Serializable {private Integer id;private String name;private String password;public User() {}public User(String name, String password) {this.name = name;this.password = password;}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;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", password='" + password + '\'' +'}';}
}
  1. 表t_user 复用之前的表
-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (`id` int(0) NOT NULL AUTO_INCREMENT,`name` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,`password` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

3 创建DAO接口UserDAO.java

package com.yuhl.dao;import com.yuhl.entity.User;/*** @author yuhl* @Date 2020/11/4 10:59* @Classname UserDao* @Description TODO*/
public interface UserDAO {//保存用户public void save(User user);
}
  1. 实现Mapper文件(对maper编程)com.yuhl.mapper/UserDAOMapper.xml
    特别注意:com.yuhl.mapper是一个文件集,不是三级包
<?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.yuhl.dao.UserDAO"> <!--接口名--><!--id:mybatis.UserDao接口中的方法面parameterType:面向对象的对象名字--><insert id="save" parameterType="user">insert into t_user(name,password) value (#{name},#{password})</insert>
</mapper>
  1. 测试
import com.yuhl.dao.UserDAO;
import com.yuhl.entity.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** @author yuhl* @Date 2020/11/4 11:06* @Classname MybatisTest* @Description 测试*/
public class MybatisTest2 {@Testpublic void test1() {ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");UserDAO userDao = (UserDAO) ctx.getBean("userDAO");userDao.save(new User("zhangsan","ddd"));}
}
  1. 结果
    在这里插入图片描述

5.Mybatis和spring整合事务控制

在这里插入图片描述
这句话告诉我们spring并没有提交事务,我们的事务是被谁提交的呢?
前面我们单独使用mybatis的时候手动提交了了事务
session.commint;
这里直接给出答案,是我们引入的第三方数据源druid控制了事务的提交。
但是在实战中我们不会让他控制我们的事务,我们会把事务的控制权交给spring,让spring来控制事务。
下一篇:18-Spring事务控制@Transactional https://blog.csdn.net/fsjwin/article/details/109497305


http://chatgpt.dhexx.cn/article/wY8apUpn.shtml

相关文章

MyBatis持久层框架

文章目录 一、Maven搭建1、本地maven仓库以及本地依赖2、idea搭建maven环境3、配置Product实体类4、配置Product接口5、配置db.properties文件6、配置SqlMapperConfig.xml文件7、配置ProductMapper.xml8、配置测试类9、运行 一、Maven搭建 1、本地maven仓库以及本地依赖 2、id…

Java数据持久层框架

一、前言 1.持久层 Java数据持久层&#xff0c;其本身是为了实现与数据源进行数据交互的存在&#xff0c;其目的是通过分层架构风格&#xff0c;进行应用&数据的解耦。 我从整体角度&#xff0c;依次阐述JDBC、Mybatis、MybatisPlus。 前者总是后者的依赖。只有在了解前…

三大框架 —— 持久层框架MyBatis

持久层框架MyBatis 1. mybatis介绍2. 执行流程3. 使用步骤代码实现举例&#xff1a;商品分类CRUD操作 4. 关联关系4.1 一对一4.2 一对多 5. 参数占位符6. 复杂搜索6.1 动态SQL语句6.2 集合参数 1. mybatis介绍 传统框架的缺点&#xff1a; 使用jdbc需要程序员创建连接&#xff…

持久层框架(Mybatis)

持久层框架 工具和框架 工具&#xff1a; JDBC -> DbUtils(QueyRunner) -> JdbcTemplate: 功能简单&#xff0c;SQL语句编写在Java代码中&#xff0c;这是硬编码&#xff0c;高耦合。 框架&#xff1a; 框架是整体解决方案。 如何进行事务控制&#xff0c;如何实现查询缓…

【Java必学框架】一文搞懂Java持久层框架Mybatis,由浅入深

文章目录 一.简介二.快速入门三.映射文件配置详解1.基本增删改查标签、属性2.动态sql2.1\标签2.2\标签 四.核心配置文件1.核心配置文件标签层级关系及作用2.配置示例3.事务管理器4.数据源5.Mapper标签6.自定义类型转换器7.插件机制 五.相应API1.工具对象2.openSession方法3.Sql…

python怎么输入根号

今天我们来说一说Python中如何实现对一个数字开平方。有三种解决办法、 下面我们分别来演示Python中数字开平方的三种方法 第一种方法&#xff1a;使用math模块&#xff0c;使用之前需要先调用,如下 第二种方法&#xff1a;使用内置函数pow(),如下 第三种方法&#xff1a;使用数…

Python-开根号的几种方式

文章目录 前言方法一方法二方法三 前言 使用Python中的自带库math、自带函数pow和自带库cmath来对数字进行开根号运算 方法一 使用&#xff1a;math.sqrt(数字) import math n int(input(数字:)) x math.sqrt(n) print(x) print(type(x)) #开根号后的类型为float方法二 使用&…

chatgpt赋能python:Python开根号:从入门到精通

Python开根号&#xff1a; 从入门到精通 Python是一种通用的高级编程语言&#xff0c;被广泛应用于数据、人工智能、网络应用、图像处理等多个领域。其中&#xff0c;数学计算是使用Python的常见场景之一&#xff0c;而在数学计算中&#xff0c;常常需要对数值进行开根号运算。…

求解任意正整数n开根号的值,不用函数求解√2(根号二),二分法求根号,定义函数fun()求根号,二分法查找

求解任意正整数n开根号的值 提示&#xff1a;理解二分法、函数调用 定义函数double fun(int n)实现 #include<bits/stdc.h> //万能函数头文件 using namespace std; double fun(int n); //定义一个求解根号的函数声明 int main() { int n;cout<<"输入想…

C语言根号作用,c语言中如何开根号运算

用math.h里封装好的函数&#xff0c;具体如下&#xff1a; 求平方根&#xff1a;double sqrt(double x) 例&#xff1a; #include #include int main(void) { double x 4.0, result; result sqrt(x); printf("The square root of %lf is %lf ", x, result); retu…

JavaScript中的乘方和开根号的使用方法

1、乘方 <script>var ikun Math.pow(4,3);console.log(ikun); </script> 2、开根号 <script>var ikun Math.sqrt(64);console.log(ikun); </script> 我们在开根号后还可以再次开根号 <script>var ikun Math.sqrt( Math.sqrt(81));console.…

python三种方法开根号(穷举法、二分法、牛顿拉夫逊法)

文章目录 方法一&#xff1a;穷举法方法二&#xff1a;二分法方法三&#xff1a;牛顿-拉夫逊算法总结 方法一&#xff1a;穷举法 positive_num int(input("输入一个正数:")) #无穷逼近法 answer0 #正数的根号结果 numGuess0 #循环次数 epsilon0.01 …

计算机开根号原理,根号的原理_怎么开的根号,有原理吗

怎么开的根号,有原理吗 JPG&#xff0c;526x296&#xff0c;128KB&#xff0c;444_250 怎么在数轴上画出根号3,求详细过程和原理 JPG&#xff0c;600x293&#xff0c;231KB&#xff0c;514_250 求根号 X 2 2 9 根号 X 3 2 4 的最小值 JPG&#xff0c;598x800&#xff0c;128KB&…

python中根号怎么输入_python中根号怎么表示

sqrt() 方法返回数字x的平方根。 以下是 sqrt() 方法的语法:&#xff08;推荐学习&#xff1a;Python视频教程&#xff09;import math math.sqrt( x ) 注意&#xff1a;sqrt()是不能直接访问的&#xff0c;需要导入 math 模块&#xff0c;通过静态对象调用该方法。 参数 x…

java 开三次根号_java里实现开根号

java里实现开根号 [2021-02-03 08:57:13] 简介: php去除nbsp的方法:首先创建一个PHP代码示例文件;然后通过“preg_replace("/(\s|\&nbsp\;| |\xc2\xa0)/", " ", strip_tags($val));”方法去除所有nbsp即可。推荐:《PHP视频教 excel中开根号的函数…

开根号的笔算算法图解_一个数的开根号怎么计算

一个数的开根号怎么计算2020-11-08 15:46:47文/钟诗贺 带根号的式子可以直接进行开平方的运算。一些特殊的根号运算有;√2≈1.414、1/2-√3≈0.5-1.732≈-1.232、2√5≈22.236≈4.236、√7-√6≈2.646-2.449≈0.197。 开平方的笔算方法 1&#xff0e;将被开方数的整数部分从个位…

chatgpt赋能python:如何在Python中表示开根号?

如何在Python中表示开根号&#xff1f; 在Python中&#xff0c;表示开根号有多种方法。本文将介绍其中最常用的三种方法&#xff0c;并对它们的优缺点进行比较&#xff0c;以便读者意识到哪种方法最适合他们的需求。 方法一&#xff1a;使用math模块的sqrt函数 在Python中&a…

python中根号怎么表示_根号python_python根号_python 根号 - 云+社区 - 腾讯云

广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 语法以下是sqrt()方法的语法 -import mathmath.sqrt( x )python注意 -此函数不可直接访问,需要导入math模块,然后需要使用math静态对象调用此函数。 2,开n次…

python开根_python如何开根号

平方根&#xff0c;又叫二次方根&#xff0c;表示为〔√&#xffe3;〕&#xff0c;如&#xff1a;数学语言为&#xff1a;√&#xffe3;164。语言描述为&#xff1a;根号下164。python学习网&#xff0c;大量的免费python基础教程&#xff0c;欢迎在线学习&#xff01; 以下…

python开根号_python 开根号

广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 语法以下是sqrt()方法的语法 -import mathmath.sqrt( x )python注意 -此函数不可直接访问,需要导入math模块,然后需要使用math静态对象调用此函数。 2,开n次…