SpringBoot入门七(整合之事务和连接池)
目标,配置Spring Boot自带默认的Hikari数据库连接池和使用
@Transactional注解进行事务配置
分析:
事务配置
1.添加事务相关的启动器依赖,mysql相关依赖
2.编写业务类UserService,使用@Transactional事务注解
3.数据库连接池hikari配置(默认的)
只需要在application配置文件中指定数据库相关参数
=========================
1.添加事务相关的启动器依赖,mysql相关依赖
<?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"> <modelVersion>4.0.0</modelVersion> <!--SpringBoot父工程--> <parent> <artifactId>spring-boot-starter-parent</artifactId> <groupId>org.springframework.boot</groupId> <version>2.3.4.RELEASE</version> </parent> <groupId>org.cc8w</groupId> <artifactId>javaboot_test</artifactId> <version>1.0-SNAPSHOT</version> <!--java编译版本,父工程已经指定了这样的变量--> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!--SpringBoot Web启动器(不用写版本跟随父版本)--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--在配置注解@ConfigurationProperties加的--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.20</version> </dependency> <!--添加数据库启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--添加mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> </project>
2.编写业务类UserService,使用@Transactional事务注解
package com.cc8w.home.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class UserService { //根据id查询 public String queryById(int id){ return "zhangsan"; } //保存用户 @Transactional public void saveUser(){ System.out.println("保存.."); } }
3.数据库连接池hikari配置(默认的)
只需要在application配置文件中指定数据库相关参数
#修改服务器端口 server.port=8080 #数据库连接(默认连接) spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mini_card spring.datasource.username=root spring.datasource.password=89757