java - Spring Boot 保存数据到数据库 休息 1 天

标签 java mysql hibernate spring-boot jvm

问题

我正在使用 SpringBoot 编写一个应用程序,使用 hibernate 将数据写入 MySQL 数据库。我使用 thymeleaf 从 HTML 表单获取实体的数据。 当我将记录保存到数据库时,它们落后 1 天,所以 2019-04-09 变成了 2019-04-08。

目前有效的方法

到目前为止,我找到的解决此问题的唯一解决方案是将我的系统时间更改为 UTC,但显然,无论我为谁编写应用程序,这都会有所不同。我在 Internet 上看到过很多关于此的主题,但大多数时候它是使用 JVM hack 修复的,如果可能的话,我想以正确的方式进行修复。

让我感到困惑的是什么

我正在使用 java.time.LocalDate,它应该不使用时区,并将此日期保存到类型为“日期”的 SQL 数据库列中。我尝试将我的数据库时区更改为 UTC,但这似乎没有什么区别。唯一有所不同的是将我的窗口时间更改为 UTC。

应用程序属性

spring.datasource.url=jdbc:mysql://localhost:3306/boxbaza?serverTimezone=UTC
spring.datasource.username=box
spring.datasource.password=box
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL55Dialect
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create

hibernate 实体

@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name = "dataUmowy")
private LocalDate dataUmowy;

Controller

@SessionAttributes("ofwca")
@Controller
public class OfwcaController {

@Autowired
private OfwcaDao ofwcaDao;

@RequestMapping(value = "/panelOfwca/daneOfwca", method = RequestMethod.POST)
public String daneOfwca(Model model, @ModelAttribute("ofwca") Ofwca ofwca){

    ofwcaDao.save(ofwca);

    model.addAttribute("title", "Dane " + ofwca.getImie() + " " + ofwca.getNazwisko());
    model.addAttribute("ofwca", ofwca);
    return "panelOfwca/daneOfwca";
}

数据访问对象

@Transactional
@Repository
public interface OfwcaDao extends CrudRepository<Ofwca, Integer> {

public List<Ofwca> findAll();

public Ofwca findByIdOfwca(Integer idOfwca);

}

html 表单

<form role="form" method="post" th:action="@{/panelOfwca/daneOfwca}" th:object="${ofwca}">

  <div class="form-group col-xs-4">
    <label for="dataUmowy">Data umowy</label>
    <input type="date" id="dataUmowy" th:field="*{dataUmowy}" class="form-control">
  </div>
</form>

最佳答案

您的 jdbc URL 出现此问题:

spring.datasource.url=jdbc:mysql://localhost:3306/boxbaza?serverTimezone=UTC

您必须按如下方式更改 jdbc 连接 URL:

spring.datasource.url=jdbc:mysql://localhost:3306/boxbaza?serverTimezone=Europe/Berlin

我已经用上面的替换解决了延迟 1 天的问题。

关于java - Spring Boot 保存数据到数据库 休息 1 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55549332/

相关文章:

java - 找不到用于签名配置的应用程序 keystore 'externalOverride'

mysql - 使用 select 语句创建自定义表 MySQL

mysql - 返回字符串中包含多个逗号分隔值的行

java - @Configuration类没有被调用

java - 如何释放多个 org.hibernate.impl.SessionFactoryImpl

java - 长溢出: Fibonacci series

java - 如何使用代码清除netbeans输出

java - Web 应用程序中的一个帐户、多个用户、多个购物车

PHP 服务器输出关于 FD_SETSIZE 的警告

java - Hibernate:使用 Ctriteria API 从两个链接表中获取数据