【问题标题】:Difficulty connecting Mysql to Spring BootMysql 与 Spring Boot 连接困难
【发布时间】:2018-12-06 02:44:31
【问题描述】:

我是 Spring Boot 的新手,一直在尝试将它连接到我的 MySql 工作台。我用 web、jdbc、jpa 和 hibernate 开始了一个新的 Spring Boot 项目,但一直卡住。

关于这个主题有很多教程,但它们都首先指出有必要进入 application.properties 文件并添加类似于以下的配置:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/mysqltutorial?useSSL=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

但是,我找到的教程都没有讨论如何找到 spring.datasource.url 甚至用户名或密码。

如何找到更新这些应用程序属性以便 Mysql 工作台连接到我的 Spring Boot 应用程序?

【问题讨论】:

    标签: java mysql spring spring-boot


    【解决方案1】:

    在你的情况下, spring.datasource.url 等于 jdbc:mysql://localhost:3306/mysqltutorial?useSSL=false

    分手:

    jdbc:mysql://localhost:3306 是对在您的机器上本地运行的 MySQL 的引用。默认情况下,MySQL 在端口 3306 上运行,但如果您愿意,可以更改它。此外,如果您想连接到在其他地方运行的数据库,则可以从 localhost 更改地址。

    mysqltutorial 是您在 MySQL 中创建的数据库的名称。

    ?useSSL=false 是连接数据库的附加属性。

    接下来,
    spring.datasource.usernamespring.datasource.password 是您在 MySQL 中用于数据库的密码和用户名。对于小型项目,您可以使用 root,但对于更严重的项目不建议使用 root,并且应该创建具有不同权限的另一个用户。

    【讨论】:

    • 所以每次我想在本地访问 mysql 数据库时,我都会使用端口 3306 并附加数据库的名称,Spring 会知道如何找到它?
    • 是的,如果你为它提供'localhost'并且它在Spring上运行的端口将能够找到它。但是,要与之交互(添加数据、删除数据等),您需要向其提供您要使用的用户的用户名和密码。
    【解决方案2】:

    Springboot 是自动生成 Java Config Object 的工具,比如 DataSource 等的实例。

    对于大多数springboot应用,如果你在springboot主类上添加@EnableAutoConfiguration或@SpringBootApplication注解,它会自动加载很多SpringBoot的config Java类。

    对于你的问题,springboot 会自动加载 DataSourceAutoConfiguration。

    下一个@EnableConfigurationProperties({DataSourceProperties.class}) 将从元数据类 DataSourceProperties.class 加载属性。

    所以元数据类 DataSourceProperties.class 解决了您的问题。

    【讨论】:

    • 我必须在我的主类中导入该类吗?
    • @Dog for SpringBoot ,它会自动加载,你只需要在你的主类上添加 \@SpringbootApplication 。
    猜你喜欢
    • 2021-10-23
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多