【SpringBoot】三:访问数据库

news2024/10/5 14:23:53

文章目录

  • 1.DataSource
  • 2.JdbcTemplate
    • 2.1 准备环境
    • 2.2 准备表和数据
    • 2.3 配置数据源
    • 2.4 JdbcTemplate访问mysql
    • 2.5 创建实体类 ArticlePO
    • 2.6 测试
      • 2.6.1 测试聚合函数
  • 3.mybatis
    • 3.1 单表CRUMD
      • 3.1.1 创建模块
      • 3.1.2 查询
      • 3.1.3 插入
      • 3.1.4 更新
      • 3.1.5 删除
    • 3.2 ResultMap
    • 3.3 SQL 提供者
    • 3.4 @One一对一查询
    • 3.5 @Many 一对多查
    • 3.6 常用配置参数
    • 3.7 MybatisAutoConfiguration
    • 3.8 合适的连接池
  • 4. 声明式事务

1.DataSource

2.JdbcTemplate

2.1 准备环境

(1)新建数据库
在这里插入图片描述
(2)创建项目
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
启动lombok
在这里插入图片描述

2.2 准备表和数据

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

2.3 配置数据源

在这里插入图片描述
【application.properties】

在这里插入图片描述
运行springboot,初始化数据库脚本。

在这里插入图片描述
之后不再初始化数据库脚本。
在这里插入图片描述

2.4 JdbcTemplate访问mysql

JdbcTemplate的方法
(1)execute 方法:可以用于执行任何 SQL 语句,常用来执行 DDL 语句。
(2)update、batchUpdate 方法:用于执行新增、修改与删除等语句。
(3)query 和 queryForXXX 方法:用于执行查询相关的语句。
(4)call 方法:用于执行数据库存储过程和函数相关的语句。

2.5 创建实体类 ArticlePO

在这里插入图片描述

2.6 测试

2.6.1 测试聚合函数

在这里插入图片描述

在这里插入图片描述

3.mybatis

3.1 单表CRUMD

3.1.1 创建模块

在这里插入图片描述

3.1.2 查询

PO【ArticlePO.java】

package com.sdnu.mybatis.po;

import lombok.Data;

import java.time.LocalDateTime;

@Data
public class ArticlePO {
    private Integer id;
    private Integer userId;
    private String title;
    private String summary;
    private Integer readCount;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

mapper【ArticleMapper.java】

package com.sdnu.mybatis.mapper;

import com.sdnu.mybatis.po.ArticlePO;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface ArticleMapper {
    //按主键查询
    @Select("""
        select id, user_id, title, summary, read_count, create_time, update_time
        from article where id = #{articleId}
        """)
    @Results(id = "BaseArticleMap", value = {
         @Result(id = true, column = "id", property = "id"),
             @Result(column = "user_id", property = "userId"),
             @Result(column = "summary", property = "title"),
             @Result(column = "summary", property = "summary"),
             @Result(column = "read_count", property = "readCount"),
             @Result(column = "create_time", property = "createTime"),
             @Result(column = "update_time", property = "updateTime")
    })
    ArticlePO selectById(@Param("articleId") Integer id);
}

3.1.3 插入

mapper【ArticleMapper.java】


public interface ArticleMapper {
     //插入
    @Insert("""
            insert into article(id, user_id, title, summary, read_count, create_time, update_time)
            value (#{id}, #{userId}, #{title}, #{summary}, #{readCount}, #{createTime}, #{updateTime})
            """)
    int insertArticle(ArticlePO articlePO);
}

3.1.4 更新

mapper【ArticleMapper.java】

package com.sdnu.mybatis.mapper;

import com.sdnu.mybatis.po.ArticlePO;
import org.apache.ibatis.annotations.*;

public interface ArticleMapper {
    @Update("""
            update article set title = #{title} where id = #{id}
            """)
    int updateArticle(@Param("title") String title, @Param("id") Integer id);
}

3.1.5 删除

package com.sdnu.mybatis.mapper;

import com.sdnu.mybatis.po.ArticlePO;
import org.apache.ibatis.annotations.*;

public interface ArticleMapper {
    @Delete("""
            delete from article where id = #{id}
            """)
    int deleteArticle(@Param("id") Integer id);
}

3.2 ResultMap

mapper【ArticleMapper.java】

package com.sdnu.mybatis.mapper;

import com.sdnu.mybatis.po.ArticlePO;
import org.apache.ibatis.annotations.*;

public interface ArticleDao {
    //根据id查询文章
    @Select("""
        select id, user_id, title, summary, read_count, create_time, update_time
        from article where id = #{articleId}
        """)
    @Results(id = "BaseArticleMap", value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "user_id", property = "userId"),
            @Result(column = "summary", property = "title"),
            @Result(column = "summary", property = "summary"),
            @Result(column = "read_count", property = "readCount"),
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "update_time", property = "updateTime")
    })
    ArticlePO selectById(@Param("articleId") Integer id);
    //根据user_id查询文章
    @Select("""
        select id, user_id, title, summary, read_count, create_time, update_time
        from article where user_id = #{userId}
        """)
    //引用结果集映射,value值是@Results中的id
    @ResultMap("BaseArticleMap")
    ArticlePO selectByUserId(@Param("userId") Integer userId);
}

@ResultMap使用两种方式:

  • 通过@Results定义列的映射关系,@ResultMap(value = “@Result的id”)
  • 在xml中定义, 在代码中使用@ResultMap(value = “xml的id”)
    xml方式:

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sdnu.mybatis.mapper.ArticleDao">
    <resultMap id="ArticleMapper" type="com.sdnu.mybatis.po.ArticlePO">
        <id column="id" property="id"/>
        <result column="user_id" property="userId" />
        <result column="read_count" property="readCount" />
        <result column="create_time" property="createTime" />
        <result column="update_time" property="updateTime" />
    </resultMap>
</mapper>

3.3 SQL 提供者

【SqlProvider.java】

package com.sdnu.mybatis.provider;

public class SqlProvider {
    public static String selectArticle(){
        return """
            select * from article where id = #{id}
           """;
    }
    public static String updateTime(){
        return """
             update article set update_time = #{newTime} where id = #{id}
            """;
    }
}

【ArticleRepository.java】

package com.sdnu.mybatis.mapper;

import com.sdnu.mybatis.po.ArticlePO;
import com.sdnu.mybatis.provider.SqlProvider;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;

public interface ArticleRepository {
    @Select("")
    @Results(id = "NewBaseArticleMap", value = {
        @Result(id = true, column = "id", property = "id"),
        @Result(column = "user_id", property = "userId"),
        @Result(column = "title", property = "title"),
        @Result(column = "summary", property = "summary"),
        @Result(column = "read_count", property = "readCount"),
        @Result(column = "create_time", property = "createTime"),
        @Result(column = "update_time", property = "updateTime")
    })
    ArticlePO selectMapper();

    @ResultMap("NewBaseArticleMap")
    @SelectProvider(type = SqlProvider.class, method = "selectArticle")
    ArticlePO selectByPrimary(Integer id);

    @UpdateProvider(type = SqlProvider.class, method = "updateTime")
    int updateTime(@Param("id") Integer id, @Param("newTime") LocalDateTime newTime);
}

【RepositoryTest.java】

package com.sdnu.mybatis;

import com.sdnu.mybatis.mapper.ArticleRepository;
import com.sdnu.mybatis.po.ArticlePO;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@SpringBootTest
public class RepositoryTest {
    @Resource
    private ArticleRepository articleRepository;
    @Test
    void testRepository(){
        ArticlePO articlePO = articleRepository.selectByPrimary(2);
        System.out.println(articlePO);
    }
    @Test
    void testRepository2(){
        int rows = articleRepository.updateTime(1, LocalDateTime.now());
        System.out.println(rows);
    }
}

3.4 @One一对一查询

3.5 @Many 一对多查

3.6 常用配置参数

https://mybatis.org/mybatis-3/zh/configuration.html#settings

3.7 MybatisAutoConfiguration

3.8 合适的连接池

4. 声明式事务

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

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

相关文章

Elasticsearch 集群部署管理

Elasticsearch 集群配置版本均为8以上 安装前准备 CPU 2C 内存4G或更多 操作系统: Ubuntu20.04,Ubuntu18.04,Rocky8.X,Centos 7.X 操作系统盘50G 主机名设置规则为nodeX.qingtong.org 生产环境建议准备单独的数据磁盘主机名 #各自服务器配置自己的主机名 hostnamectl set-ho…

【2023/05/17】smalltalk

Hello&#xff01;大家好&#xff0c;我是霜淮子&#xff0c;2023倒计时第12天。 Share His own morning are new surprises to God. 译文&#xff1a; 神自己的清晨&#xff0c;在他自己看来也是新奇的。 Life finds its wealth by the claims of the world,and its worth…

基于UIAutomation+Python+Unittest+Beautifulreport的WindowsGUI自动化测试框架

1 main.py主入口 # -*- coding:utf-8 -*- # 作者&#xff1a;虫无涯 # 日期&#xff1a;2023/2/17 # 文件名称&#xff1a;main.py # 作用&#xff1a;框架的主入口函数# codingutf-8import time from common.reportOut import report_out from common.logOut import log_out …

Wandb.init和wandb.sweep的使用准则

目录 在使用 wandb.init() 初始化函数时&#xff0c;你可以包含以下信息&#xff1a; 如果在同一个代码中多次调用 wandb.init()&#xff0c;可能会导致以下问题&#xff1a; 如果你在一个大文件中使用了 wandb.init()&#xff0c;并且想在其他小文件中使用 wandb.log() 来记…

docker-compose部署sonarqube开源代码审计和分析平台

生成文件夹 mkdir -p /docker/sonar/postgres/postgresql mkdir -p /docker/sonar/postgres/datamkdir -p /docker/sonar/sonarqube chmod 777 -R /docker/sonar/sonarqube echo "vm.max_map_count262144" > /etc/sysctl.conf sysctl -p 创建docker-compose.yml文…

Kuberentes,k8s诞生简介

一、前言 什么是k8s&#xff1f; Kuberentes 是基于容器的集群管理平台&#xff0c;它的简称&#xff0c;是K8S。有人说之所以叫k8s&#xff0c;是因为k到s中间有8个字母&#xff0c;因此叫k8s&#xff0c;也有人说&#xff0c;在使用k8s的安装配置流程中&#xff0c;共分为8…

6年测开经验面试十家大厂,整理出来的笔记...

我第一次接触自动化是在2016年。那时刚毕业一年有余&#xff0c;组内一直做手工功能测试&#xff0c;大概在2018年9月&#xff0c;部门领导要求测试组引入自动化。组内之前从没有开展过任何自动化&#xff0c;测试主管安排了一个刚入职不久的研究生同事去研究。 当时自己内心还…

STM32独立按键扫描,支持同时按下、长按、快速键值

背景 有个项目在实际应用中&#xff0c;采用8个独立按键&#xff0c;每个按键都赋予不同功能&#xff0c;实际使用过程中很多时候都是需要比较特殊的按键操作&#xff0c;例如&#xff1a;长按10s按键、长按5s按键&#xff0c;或者长按需要有快速按键值的反馈&#xff0c;这个…

wordcloud背景图多图形演示

文章目录 前言一、问题二、多图层1.部分重叠1.1背景图1.2词云图 2.完全重叠2.1背景图2.2词云图 3.不重叠3.1背景图3.2词云图 三、不同形状1.背景图2.词云图 四、代码总结 前言 大家好&#xff0c;我是空空star&#xff0c;本篇给大家分享一下wordcloud背景图多图形演示。 一、问…

网络安全真的那么好吗?

近几年&#xff0c;随着网络安全被列为国家安全战略的一部分&#xff0c;这个曾经细分的领域发展提速了不少&#xff0c;除了一些传统安全厂商以外&#xff0c;一些互联网大厂也都纷纷加码了在这一块的投入&#xff0c;随之而来的吸引了越来越多的新鲜血液不断涌入。 网络安全…

多源环境(QGIS\PostgreSQL\ARCGIS\MAXENT\R语言)支持下的SolVES 模型生态系统服务功能社会价值评估

生态系统服务是人类从自然界中获得的直接或间接惠益&#xff0c;可分为供给服务、文化服务、调节服务和支持服务4类&#xff0c;对提升人类福祉具有重大意义&#xff0c;且被视为连接社会与生态系统的桥梁。自从启动千年生态系统评估项目&#xff08;Millennium Ecosystem Asse…

Python自动化测试实现的思路及方法

Python自动化测试常用于Web应用、移动应用、桌面应用等的测试 Python自动化实现思路通常分为以下几步&#xff1a; 1. 确定自动化测试的范围和目标&#xff1a; 首先需要明确需要进行自动化测试的范围和目标&#xff0c;包括测试场景、测试用例、测试数据等。 2. 选择自动化测…

Kubernetes第2天

第四章 实战入门 本章节将介绍如何在kubernetes集群中部署一个nginx服务&#xff0c;并且能够对其进行访问。 Namespace ​ Namespace是kubernetes系统中的一种非常重要资源&#xff0c;它的主要作用是用来实现多套环境的资源隔离或者多租户的资源隔离。 ​ 默认情况下&…

机器学习——决策树原理及CART算法

问&#xff1a;CART决策树可以有多个分支结构。 答&#xff1a;错误。CART决策树每个内部节点只能有两个分支结构&#xff0c;这些分支分别对应于二进制判定的是或否。因此&#xff0c;CART决策树的每个节点将数据集分成两个较小的子集&#xff0c;其中一个子集满足某种特定条…

【系分知识】需求评审

目录 背景介绍标题目的与意义方法与流程成果展示 背景介绍 软件开发是一项复杂的工作&#xff0c;需要涉及到众多的人员和团队。在这个过程中&#xff0c;需求评审是保证项目质量和进度的关键环节。它是在项目启动之前&#xff0c;对所有的需求进行全面的评估和审查&#xff0c…

C#异步编程之数据并行及任务并行

基于Parallel.ForEach的数据并行使用 1.数据非并行 var items new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; DateTime t1 DateTime.Now; foreach (var item in items) {Console.WriteLine("数据非并行输出:{0}", item); } 2.数据并行,只要使用Parallel.ForEach P…

Unity UI -- (2) 给场景加一个标题

添加Text并将其放到正中位置 我们来增加项目的第一个UI元素&#xff1a;标题。 1. 在Hierarchy中&#xff0c;点击右键&#xff0c;选择UI > Text - TextMeshPro。如果弹出了一个TextMeshPro Importer窗口&#xff0c;选择Import TMP Essentials。TextMeshPro&#xff08;TM…

优雅地处理参数传递:Spring Boot中的技巧

目录 一&#xff1a;四种传参方式 1.1&#xff1a;在 URL 中传递参数 1.2&#xff1a;PathVariable 传递参数&#xff08;Restful 风格&#xff09; 1.3&#xff1a;在请求体中传递参数 1.4&#xff1a;在请求头中传递参数 二&#xff1a;文件上传接口测试 2.1 : test.jav…

5_推荐系统算法详解

推荐系统算法详解 主要内容常用推荐算法分类&#xff08;重点&#xff09;基于人口统计学的推荐算法用户画像 基于内容的推荐算法相似度计算 基于内容推荐系统的高层次结构特征工程数值型特征处理 类别型特征处理时间型特征处理统计型特征处理推荐系统常见反馈数据基于 UGC 的推…

【c语言】组件化打包—动态链接库dll

创作不易&#xff0c;本篇文章如果帮助到了你&#xff0c;还请点赞 关注支持一下♡>&#x16966;<)!! 主页专栏有更多知识&#xff0c;如有疑问欢迎大家指正讨论&#xff0c;共同进步&#xff01; &#x1f525;c语言系列专栏&#xff1a;c语言之路重点知识整合 &#x…