基于SpringBoot3和JDK17,集成H2数据库和jpa

2024-06-02 08:12

本文主要是介绍基于SpringBoot3和JDK17,集成H2数据库和jpa,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

基于SpringBoot3和JDK17,集成H2数据库和jpa

学会用H2数据库,为了快速写出需要处理数据关系的demo。

文章目录

  • 基于SpringBoot3和JDK17,集成H2数据库和jpa
    • 工程配置
      • pom.xml文件
      • `application.properties`文件
    • 练习H2数据库的操作
      • h2数据库的建表
      • 自增主键控制
    • 练习动态调整日志
      • 引入依赖
      • 打开管理api(application.properties)
      • 查看类的目前的日志级别
      • 修改类的日志级别
      • 测试类

工程配置

完整demo:https://download.csdn.net/download/weixin_43820556/89385337

pom.xml文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.6</version><relativePath/></parent><groupId>com.donny.demo</groupId><artifactId>h2</artifactId><version>0.0.1-SNAPSHOT</version><name>h2</name><description>Demo project for Spring Boot</description><properties><java.version>17</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>

application.properties文件

spring.application.name=h2
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.driver-class-name=org.h2.Driver
# 内存模式
#spring.datasource.url=jdbc:h2:mem:test
# 文件持久化模式
spring.datasource.url=jdbc:h2:./db/testdb;AUTO_SERVER=TRUE;
spring.datasource.username=sa
spring.datasource.password=sa
#spring.sql.init.schema-locations=classpath:db/schema.sql
spring.h2.console.path=/h2
spring.h2.console.enabled=true
logging.config=classpath:logback-spring.xml
management.endpoints.web.exposure.include=loggers

练习H2数据库的操作

h2数据库的建表

/*学生*/
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`
(`id`   INTEGER auto_increment primary key,`name` varchar(50) not null
);/*老师,一个老师可以交好几个班级*/
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher`
(`id`      INTEGER auto_increment primary key,`name`    varchar(50) not null,`subject` varchar(50) not null
);/*班级,一个学生只能在一个班级,一个班级有多名老师和学生*/
DROP TABLE IF EXISTS `grade`;
CREATE TABLE `grade`
(`id`         INTEGER auto_increment primary key,`student_id` INTEGER,`teacher_id` INTEGER,`name`       varchar(50)
);-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student`
VALUES (0, '张三');
INSERT INTO `student`
VALUES (1, '少杰');
INSERT INTO `student`
VALUES (10, '赵子龙');
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `teacher`
VALUES (0, '张老师', '语文');
INSERT INTO `teacher`
VALUES (1, '王老师', '数学');
INSERT INTO `teacher`
VALUES (2, '陈老师', '英语');
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `grade`
VALUES (1, 0, 0, '1班');
INSERT INTO `grade`
VALUES (2, 1, 2, '2班');
INSERT INTO `grade`
VALUES (3, 10, 1, 'Z班');

自增主键控制

如果单独插入了数据,则不会与JPA的数据插入时主键相关联,例如,在建表的同时,写入了id为1的数据,则JPA在新增的时候,也会不会新增id为2的数据,还是新增id为1的数据,此时即报错。本人并未解决这种问题,而是将插入数据的操作,全部交由JPA来做,是实现主键自增的统一,如果有网友可以解决此问题,可以留言。

通过JPA来操作数据库

多对多关系,建议拆解成多个1对多的关系,进行表设计。
通过注解控制外键关系

@OneToOne:双向关系,实体键的关系是一对一,此注解用在单端上
@ManyToOne:双向关系,实体键的关系是多对一,此注解用在单端上

练习动态调整日志

引入依赖

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>

打开管理api(application.properties)

management.endpoints.web.exposure.include=loggers

查看类的目前的日志级别

GET请求:http://127.0.0.1:8080/actuator/loggers/com.donny.demo.h2.controller.LogController

结果

{"effectiveLevel":"DEBUG"}

修改类的日志级别

POST请求:

http://127.0.0.1:8080/actuator/loggers/com.donny.demo.h2.controller.LogController 请求体 {"configuredLevel":"info"}

重新查询

{"configuredLevel":"ERROR","effectiveLevel":"ERROR"}

结果会是在LogController中增加一个配置项。若要取消configuredLevel,只要将请求体改为 {"configuredLevel":null}

测试类

package com.donny.demo.h2.controller;import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author 1792998761@qq.com* @version 1.0* @since 2024年06月01日 上午11:56*/
@RestController
@RequestMapping("/log")
@Slf4j
public class LogController {@GetMapping("/logger")public String loggerLevel() {log.trace("logger level is trace");log.info("logger level is info");log.debug("logger level is debug");log.warn("logger level is warn");log.error("logger level is error");return "success";}
}

开启日志级别为debug时,输出的是[2024-06-01 15:24:25,180][http-nio-8080-exec-5][ERROR][com.donny.demo.h2.controller.LogController:23] logger level is error。说明生效了。

这篇关于基于SpringBoot3和JDK17,集成H2数据库和jpa的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1023422

相关文章

Debezium 与 Apache Kafka 的集成方式步骤详解

《Debezium与ApacheKafka的集成方式步骤详解》本文详细介绍了如何将Debezium与ApacheKafka集成,包括集成概述、步骤、注意事项等,通过KafkaConnect,D... 目录一、集成概述二、集成步骤1. 准备 Kafka 环境2. 配置 Kafka Connect3. 安装 D

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

使用Navicat工具比对两个数据库所有表结构的差异案例详解

《使用Navicat工具比对两个数据库所有表结构的差异案例详解》:本文主要介绍如何使用Navicat工具对比两个数据库test_old和test_new,并生成相应的DDLSQL语句,以便将te... 目录概要案例一、如图两个数据库test_old和test_new进行比较:二、开始比较总结概要公司存在多

MySQL数据库函数之JSON_EXTRACT示例代码

《MySQL数据库函数之JSON_EXTRACT示例代码》:本文主要介绍MySQL数据库函数之JSON_EXTRACT的相关资料,JSON_EXTRACT()函数用于从JSON文档中提取值,支持对... 目录前言基本语法路径表达式示例示例 1: 提取简单值示例 2: 提取嵌套值示例 3: 提取数组中的值注意

查询SQL Server数据库服务器IP地址的多种有效方法

《查询SQLServer数据库服务器IP地址的多种有效方法》作为数据库管理员或开发人员,了解如何查询SQLServer数据库服务器的IP地址是一项重要技能,本文将介绍几种简单而有效的方法,帮助你轻松... 目录使用T-SQL查询方法1:使用系统函数方法2:使用系统视图使用SQL Server Configu

SQL Server数据库迁移到MySQL的完整指南

《SQLServer数据库迁移到MySQL的完整指南》在企业应用开发中,数据库迁移是一个常见的需求,随着业务的发展,企业可能会从SQLServer转向MySQL,原因可能是成本、性能、跨平台兼容性等... 目录一、迁移前的准备工作1.1 确定迁移范围1.2 评估兼容性1.3 备份数据二、迁移工具的选择2.1

Python中连接不同数据库的方法总结

《Python中连接不同数据库的方法总结》在数据驱动的现代应用开发中,Python凭借其丰富的库和强大的生态系统,成为连接各种数据库的理想编程语言,下面我们就来看看如何使用Python实现连接常用的几... 目录一、连接mysql数据库二、连接PostgreSQL数据库三、连接SQLite数据库四、连接Mo

Oracle数据库如何切换登录用户(system和sys)

《Oracle数据库如何切换登录用户(system和sys)》文章介绍了如何使用SQL*Plus工具登录Oracle数据库的system用户,包括打开登录入口、输入用户名和口令、以及切换到sys用户的... 目录打开登录入口登录system用户总结打开登录入口win+R打开运行对话框,输php入:sqlp

数据库使用之union、union all、各种join的用法区别解析

《数据库使用之union、unionall、各种join的用法区别解析》:本文主要介绍SQL中的Union和UnionAll的区别,包括去重与否以及使用时的注意事项,还详细解释了Join关键字,... 目录一、Union 和Union All1、区别:2、注意点:3、具体举例二、Join关键字的区别&php