【发布时间】:2019-08-28 04:20:01
【问题描述】:
问题
我正在使用 SpringBoot 编写一个应用程序,使用休眠将数据写入 MySQL 数据库。我使用 thymeleaf 从 HTML 表单中获取实体的数据。 当我将记录保存到数据库时,它们落后了 1 天,因此 2019-04-09 变为 2019-04-08。
到目前为止的效果
到目前为止,我发现解决此问题的唯一解决方案是将系统时间更改为 UTC,但显然这对于我正在为其编写应用程序的人来说会有所不同。我在互联网上看到了很多关于这方面的话题,但大多数时候它是使用 JVM hacks 修复的,如果可能的话,我想以适当的方式来做。
什么让我感到困惑
我正在使用 java.time.LocalDate,它据称不使用时区,并将此日期保存到 SQL 数据库列中,类型为“日期”。我尝试将我的数据库时区更改为 UTC,但这似乎没有什么不同。唯一不同的是将我的窗口时间更改为 UTC。
application.properties
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
休眠实体
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name = "dataUmowy")
private LocalDate dataUmowy;
控制器
@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>
【问题讨论】:
-
数据库中的列类型是什么?
-
在 MySQL 中类型是 'DATE'
标签: java mysql hibernate spring-boot jvm