问题
我正在使用 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/