将spring应用程序连接到Mysql数据库时出现问题
Posted
技术标签:
【中文标题】将spring应用程序连接到Mysql数据库时出现问题【英文标题】:Trouble connecting spring application to Mysql Database 【发布时间】:2020-11-26 20:20:59 【问题描述】:嗨,我对 Spring 学习这个春季教程比较陌生:https://spring.io/guides/gs/accessing-data-mysql/
我正在使用提供的代码并按照建议设置了 MySql 数据库,但是使用 cURL 命令会出现以下错误:
curl localhost:8080/demo/add -d name=First -d email=someemail@someemailprovider.com HTTP Status 500 ÔÇô Internal Server Errorbody font-family:Tahoma,Arial,sans-serif; h1, h2, h3, b 颜色:白色;背景颜色:#525D76; h1 字体大小:22px; h2 字体大小:16px; h3 字体大小:14px; p font-size:12px; a color:black; .line height:1px;background-color:#525D76;border:none;
HTTP 状态 500 ÔÇô 内部服务器错误
主控制器:
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();
用户.java
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;
UserRepository.java
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>
application.properties
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
Gradle.build
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 INFO 17940 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 9ms. Found 0 JPA repository interfaces.
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】:您的代码中有两个问题
1 - 您尚未将 @Repository 注释添加到您的存储库类。因此,系统无法找到任何存储库接口
2 - 你做错了 curl 命令。您正在发送姓名和电子邮件作为正文参数。理想情况下,您应该将它们作为查询参数发送。这是您在控制器中使用 @RequestParam 时所期望的
curl --location --request POST 'localhost:8080/demo/add?name=First&email=email@dds.com'
【讨论】:
我添加了@Repository 注释,curl 命令提供以下输出: curl: (6) 无法解析主机:'localhost'email' 未被识别为内部或外部命令,可运行的程序或批处理文件。 我已将您的代码(使用@Repository)复制到我的本地,它对我来说非常适合。下面是对我有用的 curl 命令 curl --location --request POST 'localhost:8080/demo/add?name=First&email=email@dds.com' 您是否将 application.properties 中的 $MYSQL_HOST:localhost 替换为实际的 mysql 地址和凭据 我正在使用 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ 并使用 curl 提示给出:(6)无法解析主机:'localhost'email'未被识别为内部或外部命令、可运行程序或批处理文件。 行,只是设置一下【参考方案2】:由于控制台中的错误,我认为您在 application.properties 中缺少此内容:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
选择与你的mysql版本相匹配的方言。
【讨论】:
【参考方案3】:需要将以下内容附加到数据源上
?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
信用 https://www.youtube.com/watch?v=2i4t-SL1VsU
【讨论】:
以上是关于将spring应用程序连接到Mysql数据库时出现问题的主要内容,如果未能解决你的问题,请参考以下文章
尝试通过 docker-compose 将 NodeJS 应用程序连接到 MySQL 映像时出现 ECONNREFUSED
将 Spring Boot 连接到 MongoLab 的 MongoDB 版本 3.0.7 时出现问题
将本地 React 前端连接到本地 Spring Boot 中间件应用程序时出现 CORS 错误
尝试连接到 localhost phpmyadmin 时出现错误