当前位置: 首页 > 知识库问答 >
问题:

将spring应用程序连接到Mysql数据库时遇到的问题

东方骏
2023-03-14
package Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import Repository.UserRepository;
import com.example.demo.Model.*;

@Controller // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {
  @Autowired // This means to get the bean called userRepository
         // Which is auto-generated by Spring, we will use it to handle the data
  private UserRepository userRepository;

  @PostMapping(path="/add") // Map ONLY POST Requests
  public @ResponseBody String addNewUser (@RequestParam String name
      , @RequestParam String email) {
    // @ResponseBody means the returned String is the response, not a view name
    // @RequestParam means it is a parameter from the GET or POST request

    User n = new User();
    n.setName(name);
    n.setEmail(email);
    userRepository.save(n);
    return "Saved";
  }

  @GetMapping(path="/all")
  public @ResponseBody Iterable<User> getAllUsers() {
    // This returns a JSON or XML with the users
    return userRepository.findAll();
  }
}
package com.example.demo.Model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class
public class User {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Integer id;

  private String name;

  private String email;

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }
}           
package Repository;

import org.springframework.data.repository.CrudRepository;

import com.example.demo.Model.User;

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete

public interface UserRepository extends CrudRepository<User, Integer> {

}
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
plugins {
    id 'org.springframework.boot' version '2.3.2.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
    id 'war'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    runtimeOnly 'mysql:mysql-connector-java'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

控制台日志,

似乎没有拾取数据库2020-08-06 16:38:44.272信息17940--[main].s.d.r.c.RepositoryConfigurationDelegate:在9ms内完成Spring数据存储库扫描。找到0个JPA存储库接口。

2020-08-06 16:38:46.196  WARN 17940 --- [         task-1] o.h.e.j.e.i.JdbcEnvironmentInitiator     : HHH000342: Could not obtain connection to query metadata : The server time zone value 'GMT Summer Time' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
2020-08-06 16:39:18.344  INFO 17940 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-06 16:39:18.344  INFO 17940 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-08-06 16:39:18.348  INFO 17940 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 4 ms
2020-08-06 16:39:18.363 ERROR 17940 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataAccessResourceFailureException: Could not create JPA EntityManager; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]] with root cause

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
```

```
2020-08-06 16:39:18.369 ERROR 17940 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
```

```
2020-08-06 16:39:18.370 ERROR 17940 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost]           : Exception Processing ErrorPage[errorCode=0, location=/error]

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DataAccessResourceFailureException: Could not create JPA EntityManager; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
```

共有1个答案

商佑运
2023-03-14

您的代码中有两个问题

1-您尚未将@repository注释添加到您的repository类中。因此,系统无法找到任何存储库接口

2-您正在执行错误的curl命令。您正在发送name和email作为正文参数。理想情况下,您应该将它们作为查询参数发送。这是您在controller中使用@RequestParam时所期望的结果

curl --location --request POST 'localhost:8080/demo/add?name=First&email=email@dds.com'
 类似资料:
  • application.yml: 我尝试从运行mysql的命名空间上的另一个pod访问该服务,因为它已经预先安装了mysql-client,并从主机访问该服务。两人都有访问数据库的权限。我还在运行应用程序的pod上tring ping。它发现服务有任何问题。 然后我尝试使用NodePort而不是ClusterIP。什么都没变。 我完全卡住了,不知道出了什么问题。如有任何帮助,不胜感激。

  • 问题内容: 我已经用create-react- app构建了一个Todo应用。我正在使用的商店基于本地存储(对象窗口的JS属性)。现在,我创建了一个MySQL数据库,并希望连接到该数据库,因此状态将显示数据库中的值,并将通过操作进行更新。 我尝试使用db.js通过“节点”控制台连接到数据库并输出值。有用。 是否可以使用此脚本将应用程序的状态连接到数据库? 问题答案: 您无法直接连接它们。 在网络浏

  • 问题内容: 我正在研究将由学校使用的应用程序。每所学校将建立自己的数据库。每个学校都会为应用程序提供自己的“设置”文件。设置文件将包含创建设置文件的特定学校的数据库URL。这样一来,使用该应用程序的学生如果想连接到其他数据库,就只能加载其他设置文件。 我的问题是,如何保护用于连接数据库的用户名和密码?因此,只有应用程序具有对数据库的读写访问权限。应用程序仅具有该特定学校的读写权限吗? 如果您需要更

  • 我在将 rails 2.3.5 应用程序连接到远程数据库时遇到问题。 在我的数据库.yml中,我有: 我得到的错误是: 无法通过套接字连接到本地 MySQL 服务器 (2) 我知道问题不在权限或用户设置上,因为当我使用相同的mysqlgem运行一个简单的ruby脚本时,它会起作用。此外,我的python脚本可以连接,我可以通过CLI与连接 我似乎无法让rails使用192.168.1.113而不是

  • 我想做的是,从我的spring boot应用程序连接到Docker中的mysql数据库。每个都在各自的容器中。 但是我一定有什么问题,因为我做不到。 为了保持简单: 应用程序属性: MySQL的docker组合: 很简单,对吧?数据库我从开始: 到目前为止,一切似乎都很顺利。 现在我已经启动了db,对于应用程序来说,这是它的docker组件。yml: 对于它的Dockerfile,我使用Linux

  • 在下面您会发现错误 2019-03-15 10:38:53.865警告1708--[main]O.H.E.J.E.I.JDBCEnvironmentInitiator:HHH000342:无法获取查询元数据的连接:服务器时区值“Paris,Madrid”无法识别或表示多个时区。如果要利用时区支持,则必须配置服务器或JDBC驱动程序(通过serverTimezone配置属性)以使用更指定的时区值。2