MySQL插入Gson日期 [英] MySQL Insert Gson Date

查看:153
本文介绍了MySQL插入Gson日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我已经使用gson将一个类序列化为包含日期的json,那么如何使用json的值使用MyBatis插入到我的h2或MySQL数据库?



下面的json使用下面的代码构造:

  Bean bean = new Bean(); 
bean.setIsPublished(true);
bean.setPublicationDate(Calendar.getInstance()。getTime());
Gson gson = new GsonBuilder()。setDateFormat(yyyy-mm-dd -hh:mm:ss)。create();
String json = gson.toJson(bean);

这使得json:

  {
isPublished:true,
publicationDate:2013-55-10-09:55:07
}

但是,当我将这个json传递给我的insert语句(使用spring的@RequestBody构造Bean)时,该服务返回400:Bad语法。



以下是MyBatis Mapper的插入语句:

  INSERT INTO bean(isPublished,publicationDate)
VALUES(#{isPublished},parseDateTime(#{publicationDate},'yyyy-mm-dd -hh:mm:ss');



当我试图插入解析的json日期时,出现了一些问题,但我不确定是什么。

解决方案

只需使用Mysql date_format函数并让数据库为您做就可以了

  date_format(#{publicationDate,jdbcType = VARCHAR},'%Y-%m-%d-%H-%i-%s')
pre>

If I have serialized a class into json, which contains dates, using gson, how can I use the value of the json to insert into my h2 or MySQL database using MyBatis?

The json below is constructed using the following code:

Bean bean = new Bean();
bean.setIsPublished(true);
bean.setPublicationDate(Calendar.getInstance().getTime());
Gson gson = new GsonBuilder().setDateFormat("yyyy-mm-dd-hh:mm:ss").create();
String json = gson.toJson(bean);

Which makes json:

{
   "isPublished":true,
   "publicationDate":"2013-55-10-09:55:07"
}

But when I pass this json to my insert statement (using spring's @RequestBody to construct the Bean) the service returns a 400: Bad Syntax.

Here's the MyBatis Mapper's insert statement:

INSERT INTO beans (isPublished, publicationDate)
VALUES (#{isPublished}, parseDateTime(#{publicationDate}, 'yyyy-mm-dd-hh:mm:ss');

When I'm trying to insert the parsed json date, something is going wrong, but I'm not sure what.

解决方案

Just use the Mysql date_format function and let the database do it for you

 date_format( #{publicationDate, jdbcType=VARCHAR}, '%Y-%m-%d-%H-%i-%s' )

这篇关于MySQL插入Gson日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆