一起来学SpringBoot(七)持久层框架

article/2025/10/14 8:35:01

springboot具有非常棒的持久层框架支持,下面我将介绍我用过的三种持久层框架进行简述使用。

由于这里操作的都是一张表,这里贴出通用的yml和建表语句 切记这里使用的是mysql8 ,5.8之前的朋友请修改后缀去掉com.mysql.cj.jdbc.Driver 中的cj。

DROP TABLE IF EXISTS `Test`;
CREATE TABLE `Test`  (`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',`age` int(11) NULL DEFAULT NULL COMMENT '年龄',`inhere` tinyint(4) NULL DEFAULT NULL COMMENT '在不在',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;SET FOREIGN_KEY_CHECKS = 1;
spring:datasource:url: jdbc:mysql://192.168.8.100:3306/FuLinTest?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=trueusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver

JdbcTemplate

首先呢看下项目结构

在这里插入图片描述

记得使用之前千万不要不加依赖哈哈

        <!-- jdbcTemplate --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>

然后贴出实体类

package com.maoxs.pojo;import lombok.Data;import java.io.Serializable;@Data
public class MyTest implements Serializable {private Long id;private String name;private int age;private Boolean inhere;public MyTest() {}public MyTest(String name, int age, Boolean inhere) {this.name = name;this.age = age;this.inhere = inhere;}public MyTest(Long id, String name, int age, Boolean inhere) {this.id = id;this.name = name;this.age = age;this.inhere = inhere;}@Overridepublic String toString() {final StringBuffer sb = new StringBuffer("MyTest{");sb.append("id=").append(id);sb.append(", name='").append(name).append('\'');sb.append(", age=").append(age);sb.append(", inhere=").append(inhere);sb.append('}');return sb.toString();}
}

然后是dao层的实现类和接口

package com.maoxs.dao;import com.maoxs.pojo.MyTest;public interface MyTestDao {MyTest selectOne(Long id);int insert(MyTest myTest);int delete(Long id);int update(MyTest myTest);
}
package com.maoxs.dao.impl;import com.maoxs.dao.MyTestDao;
import com.maoxs.pojo.MyTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;@Repository
public class MyTestDaoImpl implements MyTestDao {@Autowiredprivate JdbcTemplate jdbcTemplate;@Overridepublic MyTest selectOne(Long id) {String sql = "select id,name,age,inhere from Test where id=? ";return jdbcTemplate.queryForObject(sql, (resultSet, i) -> {MyTest myTest = new MyTest();myTest.setId(resultSet.getLong("id"));myTest.setName(resultSet.getString("name"));myTest.setAge(resultSet.getInt("age"));myTest.setInhere(resultSet.getBoolean("inhere"));return myTest;}, id);}@Overridepublic int insert(MyTest myTest) {String sql = "insert into Test (name,age,inhere) values(?,?,?)";return jdbcTemplate.update(sql, myTest.getName(), myTest.getAge(), myTest.getInhere());}@Overridepublic int delete(Long id) {String sql = "delete from Test where id=?";return jdbcTemplate.update(sql, id);}@Overridepublic int update(MyTest myTest) {String sql = "update Test set name=?,age=?,inhere=? where id=?";return jdbcTemplate.update(sql, myTest.getName(), myTest.getAge(), myTest.getInhere(), myTest.getId());}
}

然后呢编写测试看看都能用不

package com.maoxs;import com.maoxs.dao.MyTestDao;
import com.maoxs.pojo.MyTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Collections;
import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJdbcApplicationTests {@Autowiredprivate MyTestDao myTestDao;@Testpublic void insert() {MyTest myTest = new MyTest("fulin", 18, true);myTestDao.insert(myTest);}@Testpublic void selectOne() {System.out.println(myTestDao.selectOne(1L));}@Testpublic void update() {MyTest myTest = new MyTest(1L, "fulin", 18, true);myTestDao.update(myTest);}@Testpublic void delete() {myTestDao.delete(13L);}
}

ok 我这边测试都通过了


Spring Data jpa

首先呢还是先看下项目结构

在这里插入图片描述

然后使用的时候千万不要忘了加依赖

        <!-- jpa --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>

先看下实体,不要写错注解

package com.maoxs.pojo;import lombok.Data;import javax.persistence.*;
import java.io.Serializable;@Data
@Entity
@Table(name = "MyTest")
public class MyTest implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@Columnprivate String name;@Columnprivate int age;@Columnprivate Boolean inhere;
}

SpringBoot创建DAO层很多种方法其中japrepository是最强大的而且最有特色的一种,我们可以针对不同的实体创建repository接口。Spring会根据方法名称的规则进行自动生成实现,强大的不要不要的。在SpringBoot中默认已经提供了非常多的常规CRUD操作的repository,以下就是Spring为我们提供的repository接口

package com.maoxs.dao;import com.maoxs.pojo.MyTest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface TestDao extends JpaRepository<MyTest, Long> {
}

别看啥都没有功能超级牛逼 具体可以去jpa官网学习下怎么使用的 JPA 学习手册

在看下service

package com.maoxs.service;import com.maoxs.pojo.MyTest;import java.util.List;public interface TestService {void add(MyTest tset) throws Exception;void update(MyTest myTest) throws Exception;void del(Long id) throws Exception;List<MyTest> select() throws Exception;
}
package com.maoxs.service.impl;import com.maoxs.dao.TestDao;
import com.maoxs.pojo.MyTest;
import com.maoxs.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class TestServiceImpl implements TestService {@Autowiredprivate TestDao testDao;@Overridepublic void add(MyTest tset) throws Exception {testDao.save(tset);}@Overridepublic void update(MyTest myTest) throws Exception {testDao.saveAndFlush(myTest);}@Overridepublic void del(Long id) throws Exception{testDao.deleteById(id);}@Overridepublic List<MyTest> select() throws Exception {return testDao.findAll();}
}

然后写个测试类测试下

package com.maoxs;import com.maoxs.pojo.MyTest;
import com.maoxs.service.TestService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJpaApplicationTests {@Autowiredprivate TestService testService;@Testpublic void add() throws Exception {MyTest t = new MyTest();t.setAge(11);t.setInhere(false);t.setName("DesrCat");testService.add(t);}@Testpublic void update() throws Exception {MyTest t = new MyTest();t.setAge(180);t.setInhere(false);t.setName("昴先生111");t.setId(1L);testService.update(t);}@Testpublic void select() throws Exception {List<MyTest> select = testService.select();Assert.assertTrue(select.size() > 0);System.out.println(Collections.unmodifiableCollection(select));}@Testpublic void del() throws Exception {testService.del(11L);}}

我这里是都通过了你呢?


Mybatis

这里看下项目结构

在这里插入图片描述

依赖依赖依赖依赖

        <!--mybatis  --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId></dependency>

这里的yml需要加入

mybatis:mapper-locations: classpath:/mapper/*.xmltype-aliases-package: com.maoxs.pojo

然后呢是实体

package com.maoxs.pojo;import lombok.Data;import java.io.Serializable;@Data
public class MyTest implements Serializable {private Long id;private String name;private int age;private Boolean inhere;}

然后呢是dao

package com.maoxs.dao;import com.maoxs.pojo.MyTest;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface MyTestMapper {List<MyTest> findAll();
}

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.maoxs.dao.MyTestMapper"><sql id="base_sql">a.id as  id,a.name as  name,a.age as  age,a.inHere as inHere</sql><select id="findAll" resultType="com.maoxs.pojo.MyTest">select<include refid="base_sql"/>fromTest a</select>
</mapper>

切记在启动类上加入MapperScan 注解

package com.maoxs;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.maoxs")
public class SpringbootMybatisApplication {public static void main(String[] args) {SpringApplication.run(SpringbootMybatisApplication.class, args);}
}

然后是测试类

package com.maoxs;import com.maoxs.dao.MyTestMapper;
import com.maoxs.pojo.MyTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Collections;
import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMybatisApplicationTests {@Autowiredprivate MyTestMapper myTestMapper;@Testpublic void findAll() {List<MyTest> all = myTestMapper.findAll();System.out.println(Collections.unmodifiableCollection(all));}}

mybatis就不多说了,应该经常用吧实在不会的小伙伴 点击 mybatis 学习手册


然后呢就推荐大家使用mybatis的一个开源插件myabtis-plus

//TODO 后期呢我会放上使用帖子

mybatis-plus 学习手册

本博文是基于springboot2.x 如果有什么不对的请在下方留言。


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

相关文章

MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架

MyBatis是一个支持普通SQL查询&#xff0c;存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射&#xff0c;将接口和Java的POJO&#xff08;Plain Old Java Obje…

Mysql的持久层_持久层(数据层,Dao层) MyBatis框架

所谓的持久层就是把数据可以永久保持的存储到设备中,不像放到内存中那样断电就消失,一般来说,持久层为直接的理解就是对数据库的各种操作,如CRUD(增加,删除,修改,查询),更新等操作 持久层,就是把持久的动作封装成一个独立的层,这是为了降低功能代码之间的关联.创建一个更清晰的…

Spring 从入门到精通 (二十) 持久层框架 MyBatis

关键词&#xff1a;Spring | 整合 | 持久层 | MyBatis 本专栏通过理论和实践相结合&#xff0c;系统学习框架核心思想及简单原理&#xff0c;原创不易&#xff0c;如果觉得文章对你有帮助&#xff0c;点赞收藏支持博主 ✨ 目录 一、MyBatis开发步骤1.1、创建实体类1.2、实体别名…

持久层框架:Mybatis快速入门

Mybatis/Hibernate/JPA作为持久层使用广泛的框架&#xff0c;在实际的项目中有很多的追随者。这篇文章将会通过简单的实例让完全不知道Mybatis为何物的入门者迅速Catchup&#xff0c;对于有一些Java基础的入门者应该能够很快学会如何使用Mybatis进行CRUD&#xff08;增查改删&a…

持久层框架JPA与Mybatis该如何选型

一、现状描述 目前java 持久层ORM框架应用最广泛的就是JPA和Mybatis。JPA只是一个ORM框架的规范, 对该规范的实现比较完整就是Spring Data JPA&#xff08;底层基于Hibernate实现&#xff09;&#xff0c;是基于Spring的数据持久层框架&#xff0c;也就是说它只能用在Spring环…

Java持久层框架之mybatis使用

一.什么是框架,框架从何而来,为什么使用框架? 框架(framework): 1.是一系列jar包,其本质是对JDK功能的拓展.(jar包,jar:class文件的压缩包) 2.框架是一组程序的集合,包含了一系列的最佳实践,作用是解决某一个领域的问题. 最佳实践(Best Practice):实际上是无数程序员经历过无数…

数据持久层框架Mybatis

目录 1.软件开发3层架构 2.什么是框架&#xff1f; 3.传统JDBC开发的不足&#xff1f; 4.什么是Mybatis&#xff1f; 5.Mybatis入门案例&#xff1f; 6.Mybatis增删改查案例&#xff1f; 7.Mybatis代理实现DAO开发&#xff1f; 8.Mybatis高级映射 1.软件开发3层架构 软…

常见持久层框架赏析,到底是什么让你选择 MyBatis?

在绝大多数在线应用场景中&#xff0c;数据是存储在关系型数据库中的&#xff0c;当然&#xff0c;有特殊要求的场景中&#xff0c;我们也会将其他持久化存储&#xff08;如 ElasticSearch、HBase、MongoDB 等&#xff09;作为辅助存储。但不可否认的是&#xff0c;关系型数据库…

Java持久层框架

一、ORM框架 ORM:对象关系映射(英语:(Object Relational Mapping&#xff0c;简称ORM&#xff0c;或O/RM&#xff0c;或O/R mapping)&#xff0c;是一种程序技术&#xff0c;用于实现面向对象编程语言里不同类型系统的数据之间的转换 。从效果上说&#xff0c;它其实是创建了一…

17-Spring持久层框架整合

上一篇&#xff1a;16-Spring 基于注解的AOP编程、AOP总结https://blog.csdn.net/fsjwin/article/details/109482768 1.为什么Spring要与持久层框架进行整合 spring是一个优秀的框架&#xff0c;他的优秀支持就是能整合所有程序员想要让他整合的框架&#xff0c;这里所说的持…

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…