SpringBoot连接Mysql数据库

本文记录Spring Boot连接单mysql数据源和多mysql数据源的一种配置方式。


单数据源

1.在pom.xml中添加相关依赖

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

注:上述配置中的mybatis-spring-boot-starter适用于Spring 2,若使用Spring 3,需要升级到更高版本(如3.0.4),否则会报错Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required。
 

2.在配置文件中配置数据库和mapper.xml文件信息

# 数据库账号密码
spring.datasource.url=jdbc:mysql://localhost:3306/first_db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=first
spring.datasource.password=first
# mapper.xml文件路径
mybatis.mapper-locations=classpath:mappers/*.xml

3.使用

3.1.在/resources/mappers添加编写sql语句的xml文件

3.2.将接口类和SQL进行映射

有两种方法:

1. 在对应的Mapper接口类中添加@Mapper注解即可;
2. 在对应的Mapper接口类中添加@Repository注解,并在启动类添加@MapperScan("#{Mapper接口类所在包路径}")注解。

3.3.配置事务

默认开启事务(Spring 3.3.2中测试通过),无需特别配置,直接在代码中使用@Transactional注解即可。
 


多数据源

1.在pom.xml中添加相关依赖

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

2.在配置文件中配置数据库和mapper.xml文件信息

# 第一个数据库配置
spring.datasource.first.url=jdbc:mysql://localhost:3306/first_db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.first.username=first
spring.datasource.first.password=first
spring.datasource.first.mapper-locations=classpath:mappers/first/*.xml
spring.datasource.first.driver-class-name=com.mysql.cj.jdbc.Driver
# 第二个数据库配置
spring.datasource.second.url=jdbc:mysql://localhost:3306/second_db?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.second.username=second
spring.datasource.second.password=second
spring.datasource.second.mapper-locations=classpath:mappers/second/*.xml
spring.datasource.second.driver-class-name=com.mysql.cj.jdbc.Driver

3.Druid配置

第一个数据库的Druid配置

package com.example.dbtest.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.dbtest.dao.first", sqlSessionTemplateRef = "firstSqlSessionTemplate")
public class DruidFirstConfig {
    @Value("${spring.datasource.first.url:}")
    private String url;
    @Value("${spring.datasource.first.username:}")
    private String username;
    @Value("${spring.datasource.first.password:}")
    private String password;
    @Value("${spring.datasource.first.mapper-locations:}")
    private String mapperLocations;
    @Value("${spring.datasource.first.driver-class-name:}")
    private String driverClassName;

    @Bean
    public DataSource firstDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public DataSourceTransactionManager firstDataSourceTransactionManager(@Qualifier("firstDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

第二个数据库的Druid配置

package com.example.dbtest.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.dbtest.dao.second", sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class DruidSecondConfig {
    @Value("${spring.datasource.second.url:}")
    private String url;
    @Value("${spring.datasource.second.username:}")
    private String username;
    @Value("${spring.datasource.second.password:}")
    private String password;
    @Value("${spring.datasource.second.mapper-locations:}")
    private String mapperLocations;
    @Value("${spring.datasource.second.driver-class-name:}")
    private String driverClassName;

    @Bean
    public DataSource secondDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public DataSourceTransactionManager secondDataSourceTransactionManager(@Qualifier("secondDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

3.使用

3.1.在/resources/mappers/first和/resources/mappers/second添加编写sql语句的xml文件

3.2.将接口类和SQL进行映射

在对应的Mapper接口类中添加@Mapper或@Repository注解即可,无需在启动类添加@MapperScan("#{Mapper接口类所在包路径}")注解(已经在对应的配置类添加过该注解了)。

3.3.配置事务

默认开启事务(Spring 3.3.2中测试通过),无需特别配置,直接在代码中使用@Transactional注解即可,注意@Transactional除了指定rollbackFor外,还需要指定事务管理器transactionManager,事务管理器名称为对应配置类的方法名(如firstDataSourceTransactionManager、secondDataSourceTransactionManager)。

### 部署 Stable Diffusion 的准备工作 为了成功部署 Stable Diffusion,在本地环境中需完成几个关键准备事项。确保安装了 Python 和 Git 工具,因为这些对于获取源码和管理依赖项至关重要。 #### 安装必要的软件包和支持库 建议创建一个新的虚拟环境来隔离项目的依赖关系。这可以通过 Anaconda 或者 venv 实现: ```bash conda create -n sd python=3.9 conda activate sd ``` 或者使用 `venv`: ```bash python -m venv sd-env source sd-env/bin/activate # Unix or macOS sd-env\Scripts\activate # Windows ``` ### 下载预训练模型 Stable Diffusion 要求有预先训练好的模型权重文件以便能够正常工作。可以从官方资源或者其他可信赖的地方获得这些权重文件[^2]。 ### 获取并配置项目代码 接着要做的就是把最新的 Stable Diffusion WebUI 版本拉取下来。在命令行工具里执行如下指令可以实现这一点;这里假设目标路径为桌面下的特定位置[^3]: ```bash git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git ~/Desktop/stable-diffusion-webui cd ~/Desktop/stable-diffusion-webui ``` ### 设置 GPU 支持 (如果适用) 当打算利用 NVIDIA 显卡加速推理速度时,则需要确认 PyTorch 及 CUDA 是否已经正确设置好。下面这段简单的测试脚本可以帮助验证这一情况[^4]: ```python import torch print(f"Torch version: {torch.__version__}") if torch.cuda.is_available(): print("CUDA is available!") else: print("No CUDA detected.") ``` 一旦上述步骤都顺利完成之后,就可以按照具体文档中的指导进一步操作,比如调整参数、启动服务端口等等。整个过程中遇到任何疑问都可以查阅相关资料或社区支持寻求帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值